<?php
/*
	Copyright 2006, 2007, 2008, 2009, 2010 Bastiaan Grutters
    
    This file is part of Ages of Strife website.

    Ages of Strife website is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Ages of Strife website is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Ages of Strife website.  If not, see <http://www.gnu.org/licenses/>.
 */
if( !function_exists( 'formatInput' ) ) {
	function formatInput( $input ) {
		$input = ereg_replace( "[^[:space:]a-zA-Z0-9*_.-]", "", $input );
		/*$input = str_replace( ">", "", $input );
		$input = str_replace( "<", "", $input );
		$input = str_replace( "=", "", $input );
		$input = str_replace( "&", "", $input );
		$input = str_replace( "\"", "", $input );
		$input = str_replace( "\\", "", $input );
		*/
		$input = str_replace( "\t", '', $input );
		$input = trim( $input );
		$input = htmlentities( $input, ENT_QUOTES, 'UTF-8' );
		$input = addslashes( $input );
		return $input;
	}
	
	function formatEmail( $input ) {
		$input = trim( $input );
		//$input = ereg_replace( "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $input );
		$input = htmlentities( $input );
		$input = addslashes( $input );
		return $input;
	}
	
	function formatInputLetter( $input ) {
		$input = trim( $input );
		$input = htmlentities( $input, ENT_QUOTES, 'UTF-8' );
		$input = addslashes( $input );
		return $input;
	}
	
	function getPostValue( $name ) {
		if( isset( $_POST[ $name ] ) ) {
			$output = $_POST[ $name ];
		}
		else {
			$output = "";
		}
		return formatInput( $output );
	}
	
	function getSessionValue( $name ) {
		if( isset( $_SESSION[ $name ] ) ) {
			$output = $_SESSION[ $name ];
			unset( $_SESSION[ $name ] );
		}
		else {
			$output = "0";
		}
		return $output;
	}
	
	function getRandomChars( $howmany = 6 ) {
		$acceptedChars = 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789';
		$max = strlen( $acceptedChars ) - 1;
		if( $howmany > $max ) {
			$howmany = $max;
		}
		$return = null;
		for( $i = 0; $i < $howmany; $i ++ ) {
			$return .= $acceptedChars{ mt_rand( 0, $max ) };
		}
		return $return;
	}
	
	function getVillageLimit() {
		global $max_villages;
		if( !isset( $max_villages ) ) {
			require_once( "old_database_connection.php" );
			$query = "SELECT MAX(level) " .
					"FROM upgrade_status " .
					"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " " .
						" AND upgrade_id = 10 AND achieved = 1";
			$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
			
			$max_villages = 1;
			if( isset( $row[ 'MAX(level)' ] ) ) {
				//print( "max(level): " . $row[ 'MAX(level)' ] . "<br />" );
				$max_villages += $row[ 'MAX(level)' ];
			}
		}
		return $max_villages;
	}
	
	function checkRangeVillage( $village_id ) {
		require_once( "old_database_connection.php" );
		$return = false;
		$query = "SELECT x, y FROM village WHERE village_id = '" . $village_id . "'";
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		if( isset( $row[ 'x' ] ) && isset( $row[ 'y' ] ) ) {
			$x = $row[ 'x' ];
			$y = $row[ 'y' ];
			$query = "SELECT MAX(level) FROM upgrade_status WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " AND upgrade_id = 30 AND achieved = 1";
			$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
			if( isset( $row[ 'MAX(level)' ] ) ) {
				$level = $row[ 'MAX(level)' ];
			}
			else {
				$level = 0;
			}
	
			$query = "SELECT x, y " .
					"FROM village " .
					"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " AND start_place = 1";
			$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
			if( isset( $row[ 'x' ] ) ) {
				$x_home = $row[ 'x' ];
				$y_home = $row[ 'y' ];
	
				$distance2 = ( $x_home - $x ) * ( $x_home - $x ) + ( $y_home - $y ) * ( $y_home - $y );
				$maxdistance2 = ( 20 + $level * 10 ) * ( 20 + $level * 10 );
				//print( "Max distance: " . $maxdistance2 ) . "<br />\r\n";
				//print( "Distance: " . $distance2 ) . "<br />\r\n";
				if( $distance2 < $maxdistance2 ) {
					$return = true;
				}
			}
			else {
				$return = true;
			}
		}
		return $return;
	}
	
	function getTravelTime( $army_id, $to_x, $to_y, $from_x = -1, $from_y = -1, $message = false, $ruler_id = -1 ) {
		include_once( "old_database_connection.php" );
		$army_id = formatInput( $army_id );
		$query = "SELECT ruler_id, x, y " .
				"FROM army " .
				"WHERE army_id = '" . $army_id . "'";
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		if( $row[ 'ruler_id' ] == $_SESSION[ 'ruler_id' ] || $row[ 'ruler_id' ] == $ruler_id ) {
			if( $from_x == -1 || $from_y == -1 ) {
				$from_x = $row[ 'x' ];
				$from_y = $row[ 'y' ];
			}
			$query2 = "SELECT MAX(x), MAX(y) " .
					"FROM village";
			$result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
			$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
		
			$query = "SELECT * " .
					"FROM army " .
					"WHERE army_id = " . $army_id;
			$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		
			$size = $row[ 'scout' ] + $row[ 'infantry' ] + $row[ 'cavalry' ] + $row[ 'artillery' ];
			$army_name = $row[ 'name' ];
		
			if( $size == 0 ) {
				if( $message ) {
					return translate( "You can't move an empty army." );
				}
				else {
					return -1;
				}
			}
			elseif( $to_x > -1 && $to_y > -1 && $to_x <= $row2[ 'MAX(x)' ] && $to_y <= $row2[ 'MAX(y)' ] 
					&& $from_x > -1 && $from_y > -1 && $from_x <= $row2[ 'MAX(x)' ] && $from_y <= $row2[ 'MAX(y)' ] ) {
				$travel_time = sqrt( ( double ) ( ( $to_x -  $from_x ) * ( $to_x -  $from_x ) + ( $to_y -  $from_y ) * ( $to_y -  $from_y ) ) );
				if( $travel_time == 0 ) {
					if( $message ) {
						return translate( "Starting location is the same as destination." );
					}
					else {
						return 0;
					}
				}
				else {
					$bash = false;
					$turn = getCurrentTurn();
					$query = "SELECT ruler_id, name, village_id, add_turn " .
							"FROM village " .
							"WHERE x = " . $to_x . " AND y = " . $to_y;
					$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
					$row = mysql_fetch_array( $result, MYSQL_ASSOC );
					
					if( $row[ 'add_turn' ] + 800 > $turn ) { 
						// the village has been added less then 800 turns ago, we need to check if the ruler has started about the same turn or later
						$query2 = "SELECT start_turn " .
								"FROM ruler " .
								"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ];
						$result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
						$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
						if( $row2[ 'start_turn' ] + 200 < $row[ 'add_turn' ] ) {
							if( $message ) {
								return translate( 'This village is not available yet.' );
							}
							else {
								return -1;
							}
						}
					}
						
					if( isset( $row[ 'ruler_id' ] ) && ( $row[ 'ruler_id' ] == $_SESSION[ 'ruler_id' ] || $row[ 'ruler_id' ] == $ruler_id ) ) {
						$query2 = "SELECT count(*) " .
								"FROM village_buildings " .
								"WHERE village_id = " . $row[ 'village_id' ] . " AND building_id = 13";
						$result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
						$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
						if( $row2[ 'count(*)' ] > 0 ) {
							$travel_time = ( int ) round( $travel_time * 0.75 );
						}
					}
					$travel_time = ( int ) round( $travel_time );
					$travel_time = round( $travel_time );
	
					$days = translate( "days" );
					if( $travel_time == 1 ) {
						$days = translate( "day" );
					}
					if( $message ) {
						return translate( "Travel time will be" ) . " " . $travel_time . " $days.";
					}
					else {
						return $travel_time;
					}
				}
			}
			else {
				if( $message ) {
					return translate( "Starting or destination coordinates are invalid." );
				}
				else {
					return -1;
				}
			}
		}
		else {
			if( $message ) {
				return translate( "You don't own this army." );
			}
			else {
				return -1;
			}
		}
	}
	
	function getVillageStatus( $village_id ) {
		$return = -1;
		//print( "village id: $village_id<br />" );
		if( is_numeric( $village_id ) && $village_id > 0 ) {
		    $getVillageStatus_query2 = "SELECT ruler_id FROM village WHERE village_id = $village_id";
		    $getVillageStatus_result2 = mysql_query( $getVillageStatus_query2 ) or die( "Query failed : " . mysql_error() );
		    $getVillageStatus_row = mysql_fetch_array( $getVillageStatus_result2, MYSQL_ASSOC );
		    if( isset( $getVillageStatus_row[ 'ruler_id' ] ) ) {
		    	$ruler_id_tmp = $getVillageStatus_row[ 'ruler_id' ];
		    	if( $ruler_id_tmp == -1 ) {
		    		$return = 3; // owned by independents
		    	}
			    elseif( $ruler_id_tmp == $_SESSION[ 'ruler_id' ] ) {
					$return =  0; // owned by current ruler
			    }
			    else {
				    $getVillageStatus_query2 = "SELECT faction_id FROM faction_member " .
				    		"WHERE ruler_id = " . $ruler_id_tmp . " AND invited = 0 AND requested = 0";
				    $getVillageStatus_result2 = mysql_query( $getVillageStatus_query2 ) or die( "Query failed : " . mysql_error() );
				    $getVillageStatus_row = mysql_fetch_array( $getVillageStatus_result2, MYSQL_ASSOC );
			
				    $getVillageStatus_query3 = "SELECT faction_id FROM faction_member " .
				    		"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " AND invited = 0 AND requested = 0";
				    $getVillageStatus_result3 = mysql_query( $getVillageStatus_query3 ) or die( "Query failed : " . mysql_error() );
				    $getVillageStatus_row3 = mysql_fetch_array( $getVillageStatus_result3, MYSQL_ASSOC );
					if( isset( $getVillageStatus_row[ 'faction_id' ] ) && isset( $getVillageStatus_row3[ 'faction_id' ] ) && $getVillageStatus_row3[ 'faction_id' ] == $getVillageStatus_row[ 'faction_id' ] ) {
						$return = 1; // owned by allied ruler
					}
					else {
						$return = 2; // owned by hostile
					}
			    }
		    }
			else {
				$return = -1; // Not a village
			}
		}
		return $return;
	}
	
	function getStatusColor( $status ) {
		if( $status == 0 ) {
			return "green";
		}
		elseif( $status == 1 ) {
			return "blue";
		}
		elseif( $status == 2 ) {
			return "red";
		}
		elseif( $status == 3 ) {
			return "brown";
		}
	}
	
	function getCurrentTurn() {
		global $currentTurnCache;
		if( !isset( $currentTurnCache ) ) {
			$getCurrentTurn_query = "SELECT turn FROM game";
			$getCurrentTurn_result = mysql_query( $getCurrentTurn_query ) or die( "Query failed : " . mysql_error() );
			$getCurrentTurn_row = mysql_fetch_array( $getCurrentTurn_result, MYSQL_ASSOC );
			$currentTurnCache = $getCurrentTurn_row[ 'turn' ];
		}
		return $currentTurnCache;
	}
	
	function getCurrentDate() {
		$getCurrentTurn_query = "SELECT date FROM game";
		$getCurrentTurn_result = mysql_query( $getCurrentTurn_query ) or die( "Query failed : " . mysql_error() );
		$getCurrentTurn_row = mysql_fetch_array( $getCurrentTurn_result, MYSQL_ASSOC );
		return $getCurrentTurn_row[ 'date' ];
	}
	
	function printGlobalSoldiers( $ruler_id ) {
		$printGlobalSoldiers_query2 = "SELECT scouts, infantry, cavalry, artillery FROM ruler WHERE ruler_id = $ruler_id";
		$printGlobalSoldiers_result2 = mysql_query( $printGlobalSoldiers_query2 ) or die( "Query failed : " . mysql_error() );
		$printGlobalSoldiers_row = mysql_fetch_array( $printGlobalSoldiers_result2, MYSQL_ASSOC );
		print( "<table id=\"global_soldiers\">\r\n") ;
		print( "<tr id=\"even\"><td>" . translate( "Scouts" ) . "</td><td align=\"right\"><strong class=\"scouts\">" . number_format( $printGlobalSoldiers_row[ 'scouts' ] ) . "</strong></td></tr>\r\n" );
		print( "<tr id=\"even\"><td>" . translate( "Infantry" ) . "</td><td align=\"right\"><strong class=\"infantry\">" . number_format( $printGlobalSoldiers_row[ 'infantry' ] ) . "</strong></td></tr>\r\n" );
		print( "<tr id=\"even\"><td>" . translate( "Cavalry" ) . "</td><td align=\"right\"><strong class=\"cavalry\">" . number_format( $printGlobalSoldiers_row[ 'cavalry' ] ) . "</strong></td></tr>\r\n" );
		print( "<tr id=\"even\"><td>" . translate( "Artillery" ) . "</td><td align=\"right\"><strong class=\"artillery\">" . number_format( $printGlobalSoldiers_row[ 'artillery' ] ) . "</strong></td></tr>\r\n" );
		print( "</table>\r\n" );	
	}
	
	function printQuickTrades( $low_gold = false, $high_gold = false, $low_iron = false, $high_iron = false, $low_coal = false, $high_coal = false, $value_gold, $value_iron, $value_coal ) {
		$result = mysql_query( "SELECT coal_gold, iron_gold, food_gold " .
				"FROM game" ) or die ( "Query failed: " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		$gold_iron = 1 / $row[ 'iron_gold' ];
		$gold_coal = 1 / $row[ 'coal_gold' ];
		$gold_food = 1 / $row[ 'food_gold' ];
		$iron_coal = $row[ 'iron_gold' ] / $row[ 'coal_gold' ];
		$coal_iron = 1 / $iron_coal;
		$food_coal = $row[ 'food_gold' ] / $row[ 'coal_gold' ];
		$coal_food = 1 / $food_coal;
		$iron_food = $row[ 'iron_gold' ] / $row[ 'food_gold' ];
		$food_iron = 1 / $iron_food;
		if( $low_gold ) {
			if( $high_coal ) { // coal for gold
				print( "<strong class=\"coal\">" . translate( "Coal" ) . "</strong> " . translate( "for" ) . " <strong class=\"gold\">" . translate( "gold" ) . "</strong>: (" );
				$difference = $value_coal - $value_gold;
				createTradeForm( 0, 0, $difference / 64 * $gold_coal, $difference / 64, 0, 0, "Small" );
				print( ", " );
				createTradeForm( 0, 0, $difference / 32 * $gold_coal, $difference / 32, 0, 0, "Average" );
				print( ", " );
				createTradeForm( 0, 0, $difference / 16 * $gold_coal, $difference / 16, 0, 0, "Large" );
				print( ")<br />" );
			}
			if( $high_iron ) { // iron for gold
				print( "<strong class=\"iron\">" . translate( "Iron" ) . "</strong> " . translate( "for" ) . " <strong class=\"gold\">" . translate( "gold" ) . "</strong>: (" );
				$difference = $value_iron - $value_gold;
				createTradeForm( 0, $difference / 64 * $gold_iron, 0, $difference / 64, 0, 0, "Small" );
				print( ", " );
				createTradeForm( 0, $difference / 32 * $gold_iron, 0, $difference / 32, 0, 0, "Average" );
				print( ", " );
				createTradeForm( 0, $difference / 16 * $gold_iron, 0, $difference / 16, 0, 0, "Large" );
				print( ")<br />" );
			}
		}
		elseif( $high_gold ) { 
			if( $low_coal ) { // gold for coal
				print( "<strong class=\"gold\">" . translate( "Gold" ) . "</strong> " . translate( "for" ) . " <strong class=\"coal\">" . translate( "coal" ) . "</strong>: (" );
				$difference = $value_gold - $value_coal;
				createTradeForm( $difference / 64, 0, 0, 0, 0, $difference / 64 * $gold_coal, "Small" );
				print( ", " );
				createTradeForm( $difference / 32, 0, 0, 0, 0, $difference / 32 * $gold_coal, "Average" );
				print( ", " );
				createTradeForm( $difference / 16, 0, 0, 0, 0, $difference / 16 * $gold_coal, "Large" );
				print( ")<br />" );
			}
			if( $low_iron ) { // gold for iron
				print( "<strong class=\"gold\">" . translate( "Gold" ) . "</strong> " . translate( "for" ) . " <strong class=\"iron\">" . translate( "iron" ) . "</strong>: (" );
				$difference = $value_gold - $value_iron;
				createTradeForm( $difference / 64, 0, 0, 0, $difference / 64 * $gold_iron, 0, "Small" );
				print( ", " );
				createTradeForm( $difference / 32, 0, 0, 0, $difference / 32 * $gold_iron, 0, "Average" );
				print( ", " );
				createTradeForm( $difference / 16, 0, 0, 0, $difference / 16 * $gold_iron, 0, "Large" );
				print( ")<br />" );
			}
		}
		
		if( $high_coal && $low_iron ) { // coal for iron 
			print( "<strong class=\"coal\">" . translate( "Coal" ) . "</strong> " . translate( "for" ) . " <strong class=\"iron\">" . translate( "iron" ) . "</strong>: (" );
			$difference = $value_coal - $value_iron;
			createTradeForm( 0, 0, $difference / 64 * $gold_coal, 0, $difference / 64 * $gold_iron, 0, "Small" );
			print( ", " );
			createTradeForm( 0, 0, $difference / 32 * $gold_coal, 0, $difference / 32 * $gold_iron, 0, "Average" );
			print( ", " );
			createTradeForm( 0, 0, $difference / 16 * $gold_coal, 0, $difference / 16 * $gold_iron, 0, "Large" );
			print( ")<br />" );
		}
		if( $low_coal && $high_iron ) { // iron for coal
			print( "<strong class=\"iron\">" . translate( "Iron" ) . "</strong> " . translate( "for" ) . " <strong class=\"coal\">" . translate( "coal" ) . "</strong>: (" );
			$difference = $value_iron - $value_coal;
			createTradeForm( 0, $difference / 64 * $gold_iron, 0, 0, 0, $difference / 64 * $gold_coal, "Small" );
			print( ", " );
			createTradeForm( 0, $difference / 32 * $gold_iron, 0, 0, 0, $difference / 32 * $gold_coal, "Average" );
			print( ", " );
			createTradeForm( 0, $difference / 16 * $gold_iron, 0, 0, 0, $difference / 16 * $gold_coal, "Large" );
			print( ")<br />" );
		}
	}
	
	function createTradeForm( $gold_offer, $iron_offer, $coal_offer, $gold_request, $iron_request, $coal_request, $title ) {
?>
<form method="post" action="create_trade2.php"><input type="hidden" name="gold_offer" value="<?php print( round( $gold_offer ) ); ?>" /><input type="hidden" name="gold_request" value="<?php print( round( $gold_request ) ); ?>" /><input type="hidden" name="iron_offer" value="<?php print( round( $iron_offer ) ); ?>" /><input type="hidden" name="iron_request" value="<?php print( round( $iron_request ) ); ?>" /><input type="hidden" name="coal_offer" value="<?php print( round( $coal_offer ) ); ?>" /><input type="hidden" name="coal_request" value="<?php print( round( $coal_request ) ); ?>" /><input type="hidden" name="calculate" value="true" /><input type="hidden" name="multiplier" value="1" /><input type="hidden" name="from" value="0" /><input type="hidden" name="length" value="0" /><input type="hidden" name="type" value="0" /><input type="submit" value="<?php transprint( $title ); ?>" /></form>
<?php
	}
	
	function getThreadCount( $message_id ) {
		$query = "SELECT message_id FROM messages WHERE parent = $message_id AND " .
				"( message_id IN( SELECT message_id FROM message_ruler WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " ) OR sender = " . $_SESSION[ 'ruler_id' ] . " )";
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$num = mysql_numrows( $result );
		$i = 0;
		$total = 1;
		while ( $num > $i ) {
			$total += getThreadCount( mysql_result( $result, $i, "message_id" ) );
			$i ++;
		}
		return $total;
	}
	
	function isUnreadThread( $message_id ) {
		$resultIsUnreadThread = mysql_query( "SELECT seen FROM message_ruler WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " AND message_id = $message_id" ) or die ( "Query failed: " . mysql_error() );
		$rowIsUnreadThread = mysql_fetch_array( $resultIsUnreadThread, MYSQL_ASSOC );
		
		if( isset( $rowIsUnreadThread[ 'seen' ] ) && $rowIsUnreadThread[ 'seen' ] == 0 ) {
			//print_r( $rowIsUnreadThread );
			//print( " not seen yet! " );
			return true;
		}
		else {
			$queryIsUnreadThread = "SELECT message_id FROM messages WHERE parent = $message_id";
			$resultIsUnreadThread = mysql_query( $queryIsUnreadThread ) or die( "Query failed : " . mysql_error() );
			$numIsUnreadThread = mysql_numrows( $resultIsUnreadThread );
			$i = 0;
			$unread = false;
			while ( $numIsUnreadThread > $i && !$unread ) {
				$unread = isUnreadThread( mysql_result( $resultIsUnreadThread, $i, "message_id" ) );
				$i ++;
			}
			//print( " Now: " . $unread );
			return $unread;
		}
	}
	
	function setThreaded( $message_id, $seen ) {
		//print( "Setting: $message_id to $seen<br />" );
		$query = "UPDATE message_ruler SET seen = $seen WHERE message_id = " . $message_id . " AND ruler_id = " . $_SESSION[ 'ruler_id' ];
		//print( "Query: $query <br />" );
		mysql_query( $query ) or die( "Query failed : " . mysql_error() );
	
		$query = "SELECT message_id FROM messages WHERE parent = $message_id AND " .
				"( message_id IN ( SELECT message_id FROM message_ruler WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " ) OR sender = " . $_SESSION[ 'ruler_id' ] . " ) ";
		//print( "Query: $query <br />" );
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$num = mysql_numrows( $result );
		$i = 0;
		while ( $num > $i ) {
			setThreaded( mysql_result( $result, $i, "message_id" ), $seen );
			$i ++;
		}
	}
	
	function getOldestUnread( $message_id ) {
		$resultIsUnreadThread = mysql_query( "SELECT seen " .
				"FROM message_ruler " .
				"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " AND message_id = $message_id" ) or die ( "Query failed: " . mysql_error() );
		$rowIsUnreadThread = mysql_fetch_array( $resultIsUnreadThread, MYSQL_ASSOC );
		$or = $message_id;
		
		if( isset( $rowIsUnreadThread[ 'seen' ] ) && $rowIsUnreadThread[ 'seen' ] == 0 ) {
			return $message_id;
		}
		else {
			$queryIsUnreadThread = "SELECT message_id " .
					"FROM messages " .
					"WHERE parent = $message_id " .
					"ORDER BY turn DESC, timestamp DESC";
			$resultIsUnreadThread = mysql_query( $queryIsUnreadThread ) or die( "Query failed : " . mysql_error() );
			$numIsUnreadThread = mysql_numrows( $resultIsUnreadThread );
			$i = 0;
			$unread = -1;
			while ( $numIsUnreadThread > $i && $unread == -1 ) {
				$or = mysql_result( $resultIsUnreadThread, $i, "message_id" );
				$unread = getOldestUnread( mysql_result( $resultIsUnreadThread, $i, "message_id" ) );
				if( is_array( $unread ) ) {
					$unread = -1;
				}
				$i ++;
			}
			
			if( $unread != -1 ) {
				return $unread;
			}
			else {
				return Array( -1, $or );
			}
		}
	}
	
	function getPageNumber() {
		if( isset( $_GET[ 'page' ] ) ) {
			$page = formatInput( $_GET[ 'page' ] );
			if( is_numeric( $page ) ) {
				return $page;
			}
			else { 
				return 1;
			}
		}
		else {
			return 1;
		}
	}
	
	function getNextPageLink( $text = 'Next', $url = '', $vars = false ) {
		global $page, $max_page;
		if( $page < $max_page ) {
			$sign = '?';
			if( $vars ) {
				$sign = '&';
			}
			return "<a href=\"$url" . $sign . "page=" . ( $page + 1 ) . "\" title=\"$text\">$text</a>";
		}
	}
	
	function getPreviousPageLink( $text = 'Previous', $url = '', $vars = false ) {
		global $page;
		if( $page > 1 ) {
			$sign = '?';
			if( $vars ) {
				$sign = '&';
			}
			return "<a href=\"$url" . $sign . "page=" . ( $page - 1 ) . "\" title=\"$text\">$text</a>";
		}
	}
	
	function formatAddLeave( $add, $leave ) {
		$return = "";
		if( $add > 0 ) {
			$add = "+" . number_format( $add );
			if( $leave > 0 ) {
				$leave = "-" . number_format( $leave );
				$return = " ($add/$leave)";
			}
			else {
				$return = " ($add)";
			}
		}
		elseif( $leave > 0 ) {
			$leave = "-" . number_format( $leave );
			$return = " ($leave)";
		}
		return $return;
	}
	
	function printDiplomacyTab( $selected = '' ) {
		global $shoutbox;
		$seperator = " | ";
		$query = "SELECT count(*) FROM message_ruler JOIN messages ON message_ruler.message_id = messages.message_id WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " AND seen = 0 AND hide = 0";
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		$highlight2 = "";
		if( $row[ 'count(*)' ] > 0 ) {
			$highlight2 = "class=\"highlight\"";	
		}
		if( $selected == 'Factions' ) {
			print( translate( "Factions" ) . $seperator );
		}
		else {
			print( "<a href=\"diplomacy.php\">" . translate( 'Factions' ) . "</a>$seperator" );
		}
		
		$query = "SELECT faction_id " .
				"FROM faction_member " .
				"WHERE invited = 0 AND requested = 0 AND ruler_id = " . $_SESSION[ 'ruler_id' ];
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		if( isset( $row[ 'faction_id' ] ) ) {
			$faction_id = $row[ 'faction_id' ];
		}
		else {
			$faction_id = -1;
		}
		$chat_count = $shoutbox->get_unread_chat_message_count( $_SESSION[ 'ruler_id' ], $faction_id );
		if( $chat_count == 0 ) {
			$chat_count = "";
		}
		else {
			$chat_count = "($chat_count)";
		}
		
		if( $selected == 'Shoutbox' ) {
			print( translate( "Shoutbox" ) . " $chat_count$seperator" );
		}
		else {
			print( "<a href=\"shoutbox.php\">" . translate( 'Shoutbox' ) . " $chat_count</a>$seperator" );
		}
		if( $selected == 'Letters received' ) {
			print( translate( "Letters received" ) . $seperator );
		}
		else {
		 	print( "<a $highlight2 href=\"letters.php\">" . translate( 'Letters received' ) . "</a>$seperator" );
		}
		if( $selected == 'Letters sent' ) {
			print( translate( "Letters sent" ) . $seperator );
		}
		else {
			 print( "<a href=\"sent_letters.php\">" . translate( 'Letters sent' ) . "</a>$seperator" );
		}
		if( $selected == 'Send a letter' ) {
			print( translate( "Send a letter" ) . $seperator );
		}
		else {
			print( "<a href=\"send_letter.php\">" . translate( 'Send a letter' ) . "</a>$seperator" );
		}
		if( $selected == 'Trashed letters' ) {
			print( translate( "Trashed letters" ) . $seperator );
		}
		else {
			print( "<a href=\"letters.php?trashed=view\">" . translate( 'Trashed letters' ) . "</a>$seperator" );
		}
		if( $selected == 'Buddies' ) {
			print( translate( "Buddies" ) . $seperator );
		}
		else {
			print( "<a href=\"buddylist.php\">" . translate( 'Buddies' ) . "</a>$seperator" );
		}
		if( $selected == 'Horse races' ) {
			print( translate( "Horse races" ) . "<br/>\r\n" );
		}
		else {
			print( "<a href=\"horseraces.php\">" . translate( 'Horse races' ) . "</a><br/>\r\n" );
		}
	}
	
	function getMoraleString( $morale ) {
		if( $morale >= 0.90 ) {
			$morale = "Extactic";
		}
		elseif( $morale >= 0.80 ) {
			$morale = "Delighted";
		}
		elseif( $morale >= 0.70 ) {
			$morale = "Very high";
		}
		elseif( $morale >= 0.60 ) {
			$morale = "High";
		}
		elseif( $morale >= 0.50 ) {
			$morale = "Confident";
		}
		elseif( $morale >= 0.40 ) {
			$morale = "Steady";
		}
		elseif( $morale >= 0.30 ) {
			$morale = "Low";
		}
		elseif( $morale >= 0.20 ) {
			$morale = "Very Low";
		}
		elseif( $morale >= 0.10 ) {
			$morale = "Extremely low";
		}
		else {
			$morale = "Crushed";
		}
		return translate( $morale );	
	}
	
	function allow_transfer( $x, $y ) {
		$query = "SELECT faction_id FROM faction_member WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " AND requested = 0 AND invited = 0";
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		if( isset( $row[ 'faction_id' ] ) ) {
			$faction_id = $row[ 'faction_id' ];
			$query = "SELECT count(*) FROM village JOIN faction_member ON village.ruler_id = faction_member.ruler_id WHERE x = " . $x . " AND y = " . $y . " AND faction_id = $faction_id";
			$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		}
		else {
			$query = "SELECT count(*) FROM village WHERE x = " . $x . " AND y = " . $y . " AND ruler_id = " . $_SESSION[ 'ruler_id' ];
			$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		}
		return ( isset( $row[ 'count(*)' ] ) && $row[ 'count(*)' ] > 0 );
	}
	
	function getBuildingTooltip( $building_id ) {
		if( is_numeric( $building_id ) && $building_id > -1 ) {
			$query = "SELECT * FROM buildings WHERE building_id = " . $building_id;
			$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		    if( isset( $row[ 'name' ] ) ) {
		    	$return = "";
		    	$name = $row[ 'name' ];
		    	$description = translate( $row[ 'description' ] );
			    $return .= "<div class=\"building-tooltip\"><strong>" . translate( $name ) . "</strong><br /><br />\r\n";
			    
			    $return .= translate( 'Gold cost' ) . ": <strong class=\"gold\">" . number_format( $row[ 'gold_cost' ] ) . "</strong><br />\r\n";
			    $return .= translate( 'Time to build' ) . ": " . $row[ 'time_cost' ] . " " . translate( 'days' ) . "<br />\r\n";
			    $return .= translate( 'Jobs to build' ) . ": <strong class=\"jobs\">" . number_format( $row[ 'construction_jobs' ] ) . "</strong><br /><br />\r\n";
			    $return .= translate( 'Food production' ) . ": <strong class=\"food\">" . number_format( $row[ 'food_income' ] ) . "</strong><br />\r\n";
			    $return .= translate( 'Iron production' ) . ": <strong class=\"iron\">" . number_format( $row[ 'iron_income' ] ) . "</strong><br />\r\n";
			    $return .= translate( 'Coal production' ) . ": <strong class=\"coal\">" . number_format( $row[ 'coal_income' ] ) . "</strong><br />\r\n";
			    $return .= translate( 'Jobs' ) . ": <strong class=\"jobs\">" . number_format( $row[ 'jobs' ] ) . "</strong><br />\r\n";
			    $return .= translate( 'Space' ) . ": <strong class=\"" . ( $row[ 'space' ] > 0 ? 'space-used' : 'space-available' ) . '">' . number_format( abs( $row[ 'space' ] ) ) . "</strong><br />\r\n";
			    $return .= translate( 'Population growth increase' ) . ": " . round( $row[ 'population_growth' ] * 100, 2 ) . "%<br />\r\n";
			    $return .= translate( 'Houses' ) . ": <strong class=\"houses\">" . number_format( $row[ 'housing' ] ) . "</strong><br />\r\n";
			    $return .= translate( 'Defense bonus' ) . ": <strong class=\"defense-bonus\">" . round( $row[ 'defense_bonus' ] * 100 ) . "%</strong><br />\r\n";
			    $return .= translate( 'Offense bonus' ) . ": <strong class=\"offense-bonus\">" . round( $row[ 'offense_bonus' ] * 100 ) . "%</strong><br /><br />\r\n";
				
				if( $row[ 'requires' ] != -1 ) {
					$query2 = "SELECT name, building_id FROM buildings WHERE building_id = " . $row[ 'requires' ];
					$result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
					$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
				    $return .= translate( 'Requires building' ) . ": <strong>" . translate( $row2[ 'name' ] ) . "</strong><br />\r\n";
				}
				else {
				    $return .= translate( 'Requires building' ) . ": " . translate( 'none' ) . "<br />\r\n";
				}
				
				$query2 = "SELECT name, building_id FROM buildings WHERE requires = $building_id ORDER BY name";
				$result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
				$num = mysql_numrows( $result2 );
				$i = 0;
				$return .= translate( 'Allows construction of' ) . ": ";
				if( $num > 0 ) {
					while ( $i < $num ) {
						if( $i != 0 ) {
							$return .= ", ";
						}
						$return .= "<strong>" . translate( mysql_result( $result2, $i, "name" ) ) . "</strong>";
						$i ++;	
					}
				}
				else {
					$return .= " " . translate( 'none' );
				}
				$return .= "<br />\r\n";
		
				$return .= translate( 'Required upgrade' ) . ": ";
				if( $row[ 'upgrade' ] != -1 ) {
					$query2 = "SELECT name, upgrade_id FROM upgrades WHERE upgrade_id = " . $row[ 'upgrade' ];
					$result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
					$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
					$return .= "<strong>" . translate( $row2[ 'name' ] ) . "</strong>\r\n";
				}
				else {
					$return .= translate( 'none' );
				}
				$return .= "<br />\r\n";
			    
			    $return .= "<br /><strong>" . translate( 'Description' ) . "</strong><br /><pre>\n";
			    $return .= wordwrap( $description, 80 ) . "</pre>\n</div>\n";
			    $return = htmlentities( $return, ENT_COMPAT, 'UTF-8' );
			    return $return;
		    }
		    else {
		    	return translate( 'Unknown building' );
		    }
		}
		else {
			return translate( 'Invalid building id' ); 
		}
	}
	
	function print_history_tab( $selected = '' ) {
		print( "<div class=\"blok\">\r\n" );
		$seperator = " | ";
		if( $selected == '' ) {
			print( translate( "History" ) . "$seperator" );
		}
		else {
			print( "<a href=\"history.php\">" . translate( "History" ) . "</a>$seperator" );
		}
		if( $selected == 'Overview' ) {
			print( translate( "Overview" ) . "$seperator" );
		}
		else {
		 	print( "<a href=\"history_overview.php\">" . translate( "Overview" ) . "</a>$seperator" );
		}

		if( $selected == 'Search' ) {
			print( translate( "Search" ) . "$seperator" );
		}
		else {
		 	print( "<a href=\"search.php\">" . translate( "Search" ) . "</a>$seperator" );
		}
		
		$count = "";
		if( can_publish_history() ) {
			$query = "SELECT count(*) " .
					"FROM history_seen " .
					"JOIN history ON history.history_id = history_seen.history_id " .
					"WHERE hide = 0 AND visible = 0 AND history_seen.ruler_id = " . $_SESSION[ 'ruler_id' ];
			$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
			if( $row[ 'count(*)' ] > 0 ) {
				$count = " (" . $row[ 'count(*)' ] . ")";
			}
		}
		if( $selected == 'Write' ) {
			print( translate( "Write" ) . "$count" );
		}
		else {
		 	print( "<a href=\"write.php\">" . translate( "Write" ) . "$count</a>" );
		}
		print( "</div><br />\r\n" );
	}
	
	function can_edit_history( $history_id ) {
	    $query = "SELECT ruler_id, visible " .
	    		"FROM history " .
	    		"WHERE history_id = $history_id";
	    $result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		if( $row[ 'ruler_id' ] == -1 ) { // only admin can edit these
			if( isset( $_SESSION[ 'admin' ] ) && $_SESSION[ 'admin' ] == 1 ) {
				return true;
			}
			else {
				return false;
			}
		}
		else {
			if( $row[ 'ruler_id' ] == $_SESSION[ 'ruler_id' ] && $row[ 'visible' ] == 0 ) {
				// You can edit your own stories until they are published
				return true;
			}
			else {
			    $query2 = "SELECT editor " .
			    		"FROM users " .
			    		"WHERE user_id = " . $_SESSION[ 'user_id' ];
			    $result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
				$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
				if( $row2[ 'editor' ] == 1 || ( isset( $_SESSION[ 'admin' ] ) && $_SESSION[ 'admin' ] == 1 ) ) {
					// Editors can edit all stories from any user, admins can edit everything
					return true;
				}
				else {
					return false;
				}
			}
		}
	}
	
	function can_publish_history() {
		global $can_publish;
		if( isset( $can_publish ) ) {
			return $can_publish;
		}
		
		if( isset( $_SESSION[ 'admin' ] ) && $_SESSION[ 'admin' ] == 1 ) {
			return ( $can_publish = true );
		}
		else {
		    $query2 = "SELECT editor " .
		    		"FROM users " .
		    		"WHERE user_id = " . $_SESSION[ 'user_id' ];
		    $result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
			$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
			if( $row2[ 'editor' ] == 1 || ( isset( $_SESSION[ 'admin' ] ) && $_SESSION[ 'admin' ] == 1 ) ) {
				// Editors can edit all stories from any user, admins can edit everything
				return ( $can_publish = true );
			}
			else {
				return ( $can_publish = false );
			}
		}	
	}
	
	function isEmptySector( $sector = -1, $width = -1 ) {
		if( $sector == -1 || $width == -1 ) {
			return false;
		}
		else {
			$base_value = $sector % $width;
			if( ( $base_value > 0 && $base_value % 3 == 0 ) || ( ceil( $sector / $width ) ) % 3 == 0 ) {
				return true;
			}
			else {
				return false;
			}
		}
	}
	
	function search_history( $filter, $written, $sort, $asc, $page = 1 ) {
		if( $sort == 'relevance' && $filter != '' ) {
			$query = "SELECT history.*, " .
					"( MATCH ( history.title, history.text ) AGAINST ( '$filter' IN BOOLEAN MODE ) ) AS score " .
					"FROM history";
		}
		elseif( $sort == 'rating' ) {
			$query = "SELECT history.*, ( IFNULL( ( SELECT SUM(history_rating.score) " .
				    		"FROM history_rating " .
				    		"JOIN history_tags ON history_tags.tag_id = history_rating.tag_id " .
				    		"WHERE history_rating.history_id = history.history_id AND positive >= negative ), 0 ) - " .
							" IFNULL( ( SELECT SUM(history_rating.score) " .
				    		"FROM history_rating " .
				    		"JOIN history_tags ON history_tags.tag_id = history_rating.tag_id " .
				    		"WHERE history_rating.history_id = history.history_id AND positive < negative ), 0 ) ) " .
				    	"AS score " .
				    	"FROM history";
		}
		else {
			$query = "SELECT history.*, history.turn AS score FROM history";
		}
		
		$where = " WHERE visible = 1 AND turn <= " . getCurrentTurn();
		if( $filter != '' ) {
			$where .= " AND ( MATCH ( history.title, history.text ) AGAINST ( '$filter' IN BOOLEAN MODE ) )";
		}
		
		if( $written == 1 ) {
			$where .= " AND ruler_id != -1";
		}
		elseif( $written == -1 ) {
			$where .= " AND ruler_id = -1";
		}
		
		$sort = " ORDER BY score DESC";
		if( $asc ) {
			$sort = " ORDER BY score ASC";
		}
		
		$limit = " LIMIT " . ( 10 * ( $page - 1 ) ) . ", " . 10;
		
		$query .= $where . $sort . $limit;
		//print( "The search query: $query <br /><br />" );
	    $result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
	    $items = Array();
	    while ( $row = mysql_fetch_object( $result ) ) {
			$items[] = $row;
	    }
		return $items;
	}
	
	function count_search_history( $filter, $written ) {
		$query = "SELECT count(*) FROM history";
		
		$where = " WHERE visible = 1 AND turn <= " . getCurrentTurn();
		if( $filter != '' ) {
			$where .= " AND ( MATCH ( history.title, history.text ) AGAINST ( '$filter' IN BOOLEAN MODE ) )";
		}
		
		if( $written == 1 ) {
			$where .= " AND ruler_id != -1";
		}
		elseif( $written == -1 ) {
			$where .= " AND ruler_id = -1";
		}
		
		$query .= $where;
	    $result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
	    $row = mysql_fetch_array( $result, MYSQL_ASSOC );
		return $row[ 'count(*)' ];
	}	
	
	function get_morale_string( $morale = 0.8 ) {
		if( $morale <= 0.2 ) {
			return "<strong class=\"red\">" . translate( 'Terrible' ) . "</strong>";
		}
		elseif( $morale <= 0.4 ) {
			return "<strong class=\"red\">" . translate( 'Low' ) . "</strong>";
		}
		elseif( $morale <= 0.6 ) {
			return "<strong>" . translate( 'Average' ) . "</strong>";
		}
		elseif( $morale <= 0.8 ) {
			return "<strong>" . translate( 'Great' ) . "</strong>";
		}
		else {
			return "<strong class=\"green\">" . translate( 'Fantastic' ) . "</strong>";
		}
	}
	
	function get_total_military() {
		return get_total_deployed_military() + get_total_reserves_military();
	}
	
	function get_total_deployed_military() {
	    global $total_deployed_military;
	    if( isset( $total_deployed_military ) ) {
	    	return $total_deployed_military;
	    }
	    else {
		    $query2 = "SELECT SUM( scout + infantry + cavalry + artillery ) " .
		    		"FROM army " .
		    		"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ];
		    $result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
			$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
			$total_deployed_military = $row2[ 'SUM( scout + infantry + cavalry + artillery )' ];
			return $total_deployed_military;
	    }
	}
	
	function get_total_reserves_military() {
	    global $total_reserves_military;
	    if( isset( $total_reserves_military ) ) {
	    	return $total_reserves_military;
	    }
	    else {
		    $query2 = "SELECT recruits, scouts, infantry, cavalry, artillery " .
		    		"FROM ruler " .
		    		"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ];
		    $result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
			$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
			$total_reserves_military = $row2[ 'recruits' ] + $row2[ 'scouts' ] + $row2[ 'infantry' ] + $row2[ 'cavalry' ] + $row2[ 'artillery' ];
		    /*$query2 = "SELECT SUM(scouts), SUM(infantry), SUM(cavalry), SUM(artillery) " .
		    		"FROM transfer " .
		    		"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ];
		    $result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
			$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
			$total_reserves_military += $row2[ 'SUM(scouts)' ] + $row2[ 'SUM(infantry)' ] + $row2[ 'SUM(cavalry)' ] + $row2[ 'SUM(artillery)' ];*/
			return $total_reserves_military;
	    }
	}	
	
	function get_reputation_string( $score, $experience ) {
		$reputation = translate( "Unknown" );
		$rep_points = $experience + $score * 0.001;
		if( $rep_points >     10000000000 ) {
			$reputation = translate( "God of Strife" );	
		}
		elseif( $rep_points > 1000000000 ) {
			$reputation = translate( "Immortal emperor" );	
		}
		elseif( $rep_points > 100000000 ) {
			$reputation = translate( "Glorious strategist" );	
		}
		elseif( $rep_points >  10000000 ) {
			$reputation = translate( "Battle master" );
		}
		elseif( $rep_points >   1000000 ) {
			$reputation = translate( "Grand warlord" );
		}
		elseif( $rep_points >    100000 ) {
			$reputation = translate( "Field marshal" );	
		}
		elseif( $rep_points >     10000 ) {
			$reputation = translate( "General" );
		}
		elseif( $rep_points >      1000 ) {
			$reputation = translate( "Ambitious officer" );
		}
		elseif( $rep_points >       100 ) {
			$reputation = translate( "Skirmisher" );	
		}
		elseif( $rep_points >        10 ) {
			$reputation = translate( "Scout" );
		}
		return $reputation;		
	}	
	
	function get_random_officers_name() {
		global $language, $dal;
		$first = Array( 'en' => Array( 'James', 'Jeffrey', 'Jim', 'Henry', 'William', 'Irvin', 'Charles', 'George', 'Seth',
												 'Richard', 'Harry', 'Daniel', 'Howard', 'Louis', 'Alan', 'Robert', 'John', 'Benjamin',
												 'Dan', 'Steven', 'Micheal', 'Hector', 'Gilbert', 'Alfred', 'Boris', 'Ben', 'Barry', 'Jason',
												 'Peter', 'Carl', 'Arthur' ),
							 'de' => Array( 'Joseph', 'Sebastian', 'Johan', 'Jonathan', 'Friedrich', 'Wilhelm', 'Klaus', 'Hans',
							 					 'Erwin', 'Heinz', 'Sigfried', 'Otto', 'Simon', 'Karl' ),
							 'nordic' => Array( 'Olav', 'Oscar', 'Stefan', 'Jesper', 'Lars', 'Janus', 'Engelbrekt', 'Alfred', 'Bjorn',
							 						  'Dure', 'Dan', 'Dag', 'Edda', 'Egron', 'Goda' ),
							 'russian' => Array( 'Archibald', 'Boris', 'Mori', 'Bronislav', 'Vasil', 'Vladimir', 'Blagoj', 'Ilyo',
							 							'Ivan', 'Georgi', 'Taras', 'Severyn', 'Borys', 'Symon', 'Vadym', 'Bohdan', 'Nikolay',
							 							'Nikolov', 'Yane', 'Janus', 'Piotr', 'Zevulun' ),
							 'nl' => Array( 'Hans', 'Willem', 'Otto', 'David', 'Johannes', 'Floris', 'Michiel', 'Hugo', 'Johan',
							 					 'Frederik', 'Piet', 'Maarten', 'Cornelis', 'Jacob', 'Joost', 'Jan', 'Christiaan', 'Antonie',
							 					 'Thomas' ),
							 'fr' => Array( 'Mathieu', 'Emeric', 'Pierre', 'Philip', 'Benoit', 'Armand', 'Arturo', 'Alain', 'Andre',
							 					 'Arnaud', 'Dominique', 'Claude', 'Denis', 'Emile', 'Gerard', 'Gilles', 'Jean', 'Leon', 'Jerome', 
												 'Michel', 'Maurice', 'Philippe', 'Stephane', 'Victor', 'Tristan', 'Thierry', 'Petro' ),
							 'spanish' => Array( 'Antonio', 'Marcus', 'Claudio', 'Julian', 'Marco', 'Raoul', 'Pedro', 'Jose', 'Mario', 
													  'Joao', 'Ronaldo', 'Carlos', 'Paolo', 'Federico' ),
							 'eastern' => Array( 'Zhang', 'Saneyuki', 'Chi', 'Dusan', 'Phan', 'Chen', 'Chan', 'Lin', 'Huang', 'Li', 'Wu', 
													  'Liu', 'Cai', 'Hristo' ),
							 'arabic' => Array( 'Mehrdad', 'Mohammad', 'Ali', 'Farzan', 'Bahar' ) );

		$last = Array(  'en' => Array( 'Welsley', 'Jameson', 'Morgenson', 'Rutherford', 'Varnsen', 'Smith', 'Johnson', 'Hogg', 
												'Higgs', 'Somerset', 'McDowell', 'Cooper', 'Harris', 'Newland', 'Charlton', 'Phelps',
												'Martins', 'Andersson', 'Stark', 'Webb', 'Temple', 'Leeke', 'Harper', 'Carlyle' ),
							 'de' => Array( 'von Klewinstall', 'von Schallhausen', 'Schillings', 'Braunbergen', 'Fitzel', 'Beurling',
							 					 'Oirich', 'Breitbart', 'Hasselriis', 'von Roon', 'Wallenberg', 'Havenstein', 'Mirrunst' ),
							 'nordic' => Array( 'Magnusson', 'Larsen', 'Engelbrektsson', 'Andersson', 'Wallenberg', 'Malandragem',
							 						  'Mattsson', 'Eriksson', 'Gunnarsson', 'Olavson', 'Larsson', 'Bjornsson', 'Edstrom',
							 						  'Blomqvist' ),
							 'russian' => Array( 'Rozgomev', 'Bretchiski', 'Brachlaf', 'Chekznof', 'Armelof', 'Gromchevsky', 'Pervlar',
							 							'Lanstavo', 'Maffitt', 'Levski', 'Botev', 'Jankov', 'Toshev', 'Voyvoda', 'Kolov',
							 							'Uzunov', 'Delchev', 'Sandanski', 'Dobeln', 'Majstorovic', 'Rolovic', 'Lepky', 
														'Bogolyubov', 'Khmelnytsky', 'Voinovsky', 'Hetman', 'Petliura', 'Paton', 'Nalyvaiko', 
														'Fedorovych', 'Orlev' ),
							 'nl' => Array( 'de Ruijter', 'van den Vondel', 'Cats', 'Huygens', 'Visscher', 'Bredero', 'Hooft', 'de Ruyter',
							 					 'van Riebeeck', 'van Rijn', 'Hein', 'Adriaanszoon', 'de Groot', 'de Gruyter', 'van Oldenbarneveldt',
							 					 'Maurits', 'van Leeuwenhoek', 'Drebbel', 'van der Heyden', 'van Brunswijk' ),
							 'fr' => Array( 'du Valle', 'Giraldi', 'Lebrun', 'Mairesse', 'Dreyfus', 'le Brun', 'Guynemer', 'de Charmettes', 
												 'Geison', 'Burnett', 'Jonquet', 'Hermant', 'Tiradentes', 'Arnarof' ),
							 'spanish' => Array( 'Romero', 'El Greco', 'Aeson', 'Bonafacio', 'Agius', 'Giraldi', 'Barbados', 'da Costa',
							 							'del Rei', 'de Andrade', 'Parreira' ),
							 'eastern' => Array( 'Naratas', 'Miao', 'Chung', 'Zun', 'Nagayoshi', 'Phung', 'Akiyama', 'La', 'Wang', 'Yang', 
														'Liang', 'Han', 'Teng', 'Feng', 'Xiao', 'Wei', 'Tu', 'Chiang', 'Tien', 'Su', 'Yuan', 'Peng' ),
							 'arabic' => Array( 'Abadi', 'Hadad', 'Nassar', 'Masif', 'Touma', 'Sarraf', 'Touma', 'Samaha', 'Mansour', 'Kassis',
							 						  'Halabi', 'Mustafa', 'Qureshi', 'Zogby' ) );
		
		$statement = $dal->prepare( 'SELECT officer_suggest_global ' .
				'FROM users ' .
				'JOIN ruler ON ruler.user_id = users.user_id ' .
				'WHERE ruler_id = :ruler_id' );
		$statement->bindParam( ':ruler_id', $_SESSION[ 'ruler_id' ], PDO::PARAM_INT );
		$useGlobalNames = $dal->getValue( $statement );
		
		if( $useGlobalNames == 1 ) {
			$rand = mt_rand( 0, count( $first ) - 1 );
			$count = 0;
			foreach( $first AS $key => $value ) {
				if( $count == $rand ) {
					$subset = $key;
					break 1;
				}
				$count ++;
			}
		}
		else {
			if( isset( $first[$language] ) ) {
				$subset = $language;
			}						
			elseif( $language == 'sv' ) {
				$subset = 'nordic';
			}
			elseif( $language == 'bg' ) {
				$subset = 'russian';
			}
			elseif( $language == 'br' ) {
				$subset = 'spanish';
			}
			else {
				$rand = mt_rand( 0, count( $first ) - 1 );
				$count = 0;
				foreach( $first AS $key => $value ) {
					if( $count == $rand ) {
						$subset = $key;
						break 1;
					}
					$count ++;
				}
			}
		}
		
		$name = $first[$subset][mt_rand( 0, count( $first[$subset] ) - 1 )] . ' ' . $last[$subset][mt_rand( 0, count( $last[$subset] ) - 1 )];
		
		$query = "SELECT count(*) " .
				"FROM officers " .
				"WHERE name LIKE '$name%'";
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		$count = $row[ 'count(*)' ];
		$add = "";
		if( $count == 0 ) {
			return $name;
		}
		elseif( $count == 1 ) { 
			$add = ' 2nd'; 
		}
		elseif( $count == 2 ) { 
			$add = ' 3rd'; 
		}
		elseif( $count > 2 ) { 
			if( $count > 19 && $count % 10 == 0 ) {
				$add = ' ' . ( $count + 1 ) . 'st ';
			}
			elseif( $count > 19 && $count % 10 == 1 ) {
				$add = ' ' . ( $count + 1 ) . 'nd ';
			}
			elseif( $count > 19 && $count % 10 == 2 ) {
				$add = ( $count + 1 ) . 'rd ';
			}
			else {
				$add = ' ' . ( $count + 1 ) . 'th ';
			}
		}
		return $name . $add;
	}
	
	function get_random_army_name() {
		$query = "SELECT army_names, premium " .
				"FROM users " .
				"WHERE user_id = " . $_SESSION[ 'user_id' ];
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		if( $row[ 'premium' ] > 0 && $row[ 'army_names' ] != '' ) {
			$name = $row[ 'army_names' ];
		}
		else {
			$type = Array( "Infantry", "Cavalry", "Artillery", 
								"Volunteers", "Foreign Legion", "Battalion", 
								"Army", "Regiment", "Force", "Explorers", 
								"Scouts", "Company", "Rangers", "Horse Guards", 
								"Dragoons", "Hussars", "Rifle Corps", "Brigade", 
								"Fusiliers", "Dragoon Guards" );
			$name = $type[mt_rand( 0, count( $type ) - 1 )];
		}
		
		$query = "SELECT count(*) " .
				"FROM army " .
				"WHERE name LIKE '%$name'";
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		$count = $row[ 'count(*)' ];
		if( $count == 0 ) {
			$add = '1st ';
		}
		elseif( $count == 1 ) { 
			$add = '2nd '; 
		}
		elseif( $count == 2 ) { 
			$add = '3rd '; 
		}
		elseif( $count > 2 ) { 
			if( $count > 19 && $count % 10 == 0 ) {
				$add = ( $count + 1 ) . 'st ';
			}
			elseif( $count > 19 && $count % 10 == 1 ) {
				$add = ( $count + 1 ) . 'nd ';
			}
			elseif( $count > 19 && $count % 10 == 2 ) {
				$add = ( $count + 1 ) . 'rd ';
			}
			else {
				$add = ( $count + 1 ) . 'th ';
			}
		}
		return $add . $name;
	}
	
	function get_comments( $history_id, $parent_id = -1 ) {
	    $query = "SELECT * " .
	    		"FROM comments " .
	    		"WHERE history_id = $history_id AND parent_id = $parent_id " .
	    		"ORDER BY timestamp ASC";
	    $result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
	    $num = mysql_numrows( $result );
	    $items = Array();
	    while ( $row = mysql_fetch_object( $result ) ) {
			$items[] = $row;
	    }
		return $items;
	}
	
	function print_comments( $comments, $odd, $level = 0 ) {
		$first = true;
		$modifier = " even";
		if( $odd ) {
			$modifier = " odd";
		}
		
		foreach( $comments AS $comment ) {
			$query = "SELECT name " .
		    		"FROM ruler " .
		    		"WHERE ruler_id = " . $comment->ruler_id;
		    $result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
			$ruler_name = $row[ 'name' ];
			if( !$first ) {
				print( "<br />" );
			}
?>
			<a name="comment-<?php print( $comment->comment_id ); ?>" class="hidden"></a>
			<div class="comment<?php print( $modifier ); ?>" id="comment-<?php print( $comment->comment_id ); ?>">
				<?php transprint( 'By' ); ?> <a href="../overview/ruler.php?name=<?php print( $ruler_name ); ?>"><?php print( $ruler_name ); ?></a> <?php transprint( 'on' ); ?> <?php print( $comment->date ); ?><br />
				<pre><?php print( wordwrap( stripslashes( $comment->content ), 80, "\r\n" ) ); ?></pre>
<?php
			if( $level < 10 ) {
?>
				<a class="reply-to-link" href="javascript:void(null)" onclick="replyTo( <?php print( $comment->comment_id ); ?>)" title="Reply to this comment"><small><?php transprint( 'Reply here' ); ?></small></a>
<?php
			}
			else {				
?>
				<small>(<?php transprint( 'Can\'t comment below this level' ); ?>)</small>
<?php
			}
			print_comments( get_comments( $comment->history_id, $comment->comment_id ), !$odd, $level + 1 );
?>
			</div> <!-- close comment -->
<?php
			$first = false;
		}
	}
	
	function get_comment_count( $history_id ) {
		$query = "SELECT count(*) " .
	    		"FROM comments " .
	    		"WHERE history_id = " . $history_id;
	    $result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		return $row[ 'count(*)' ];
	}
	
	function toggle_history_subscription( $history_id, $ruler_id, $force = false ) {
		$query = "SELECT count(*) " .
	    		"FROM history_subscription " .
	    		"WHERE history_id = $history_id AND ruler_id = $ruler_id";
	    $result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		if( $row[ 'count(*)' ] == 0 ) {
			$query = "INSERT INTO history_subscription " .
		    		"( history_id, ruler_id )" .
		    		"VALUES( $history_id, $ruler_id )";
		    mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		    return true;
		}
		elseif( !$force ) {
			$query = "DELETE FROM history_subscription " .
		    		"WHERE history_id = $history_id AND ruler_id = $ruler_id";
		    mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			return false;
		}
		else {
			return true;
		}
	}
	
	function check_subscription( $history_id, $ruler_id = -1 ) {
		if( $ruler_id == -1 ) {
			$ruler_id = $_SESSION[ 'ruler_id' ];
		}
		$query = "SELECT count(*) " .
	    		"FROM history_subscription " .
	    		"WHERE history_id = $history_id AND ruler_id = $ruler_id";
	    $result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		return ( $row[ 'count(*)' ] == 1 );
	}
	
	function get_army_direction( $army_id ) {
		$query = "SELECT * " .
	    		"FROM army " .
	    		"WHERE army_id = $army_id";
	    $result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$row = mysql_fetch_array( $result, MYSQL_ASSOC );
		if( $row[ 'travel' ] > 0 ) {
		    $query2 = "SELECT order_value, order_value2 " .
		    		"FROM army_orders " .
		    		"WHERE army_id = $army_id AND rank = 0";
		    $result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
		    $row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );		    	
			
			$direction = atan2( -$row[ 'y' ] + $row2[ 'order_value2' ], $row[ 'x' ] - $row2[ 'order_value' ] ) + pi();
			while( $direction < 0 ) {
				$direction += pi() * 2;
			}
			//print( "direction: $direction <br />" );
			//print( "direction graden: " . ( $direction / pi() * 180 ) . "<br />" );
			$eight_pi = 0.125 * pi();
			$sixteenth_pi = 0.5 * $eight_pi;
			//print( "eight_pi: $eight_pi <br />" );
			//print( "sixteenth_pi: $sixteenth_pi <br />" );
			if( $direction > $sixteenth_pi && $direction <= $eight_pi + $sixteenth_pi ) {
				return translate( 'East north east' );
			}
			elseif( $direction > $eight_pi + $sixteenth_pi && $direction <= 2 * $eight_pi + $sixteenth_pi ) {
				return translate( 'North east' );
			}
			elseif( $direction > 2 * $eight_pi + $sixteenth_pi && $direction <= 3 * $eight_pi + $sixteenth_pi ) {
				return translate( 'North north east' );
			}
			elseif( $direction > 3 * $eight_pi + $sixteenth_pi && $direction <= 4 * $eight_pi + $sixteenth_pi ) {
				return translate( 'North' );
			}
			elseif( $direction > 4 * $eight_pi + $sixteenth_pi && $direction <= 5 * $eight_pi + $sixteenth_pi ) {
				return translate( 'North north west' );
			}
			elseif( $direction > 5 * $eight_pi + $sixteenth_pi && $direction <= 6 * $eight_pi + $sixteenth_pi ) {
				return translate( 'North west' );
			}
			elseif( $direction > 6 * $eight_pi + $sixteenth_pi && $direction <= 7 * $eight_pi + $sixteenth_pi ) {
				return translate( 'West north west' );
			}
			elseif( $direction > 7 * $eight_pi + $sixteenth_pi && $direction <= 8 * $eight_pi + $sixteenth_pi ) {
				return translate( 'West' );
			}
			elseif( $direction > 8 * $eight_pi + $sixteenth_pi && $direction <= 9 * $eight_pi + $sixteenth_pi ) {
				return translate( 'West south west' );
			}
			elseif( $direction > 9 * $eight_pi + $sixteenth_pi && $direction <= 10 * $eight_pi + $sixteenth_pi ) {
				return translate( 'South west' );
			}
			elseif( $direction > 10 * $eight_pi + $sixteenth_pi && $direction <= 11 * $eight_pi + $sixteenth_pi ) {
				return translate( 'South south west' );
			}
			elseif( $direction > 11 * $eight_pi + $sixteenth_pi && $direction <= 12 * $eight_pi + $sixteenth_pi ) {
				return translate( 'South' );
			}
			elseif( $direction > 12 * $eight_pi + $sixteenth_pi && $direction <= 13 * $eight_pi + $sixteenth_pi ) {
				return translate( 'South south east' );
			}
			elseif( $direction > 13 * $eight_pi + $sixteenth_pi && $direction <= 14 * $eight_pi + $sixteenth_pi ) {
				return translate( 'South east' );
			}
			elseif( $direction > 14 * $eight_pi + $sixteenth_pi && $direction <= 15 * $eight_pi + $sixteenth_pi ) {
				return translate( 'East south east' );
			}
			else {
				return translate( 'East' );
			}
		}
		else { 
			return translate( 'None' );
		}
	}
	
	function get_officer_free_skillpoints( $officer_id, $experience = -1, $scouting = -1, $offense = -1, $defense = -1, $ranking = -1, $persuasion = -1 ) {
		if( $experience == -1 ) {
			$query = "SELECT experience, scouting, offense, defense, ranking " .
		    		"FROM officer " .
		    		"WHERE officer_id = $officer_id";
		    $result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
			$experience = $row[ 'experience' ];
			$scouting = $row[ 'scouting' ];
			$offense = $row[ 'offense' ];
			$defense = $row[ 'defense' ];
			$ranking = $row[ 'ranking' ];
			$persuasion = $row[ 'persuasion' ];
		}
		
		if( $experience >= 90 ) {
			$total_skill_points = floor( log( $experience / 40, 2.25 ) );
			if( $total_skill_points > 25 ) {
				$total_skill_points = 25;
			}
			$used_skill_points = $scouting + $offense + $defense + $ranking + $persuasion;
			return $total_skill_points - $used_skill_points;
		}
		else {
			return 0;
		}
	}
	
	function print_operations_tab( $selected ) {
		if( $selected == 'Map' ) {
			$military = translate( 'Map' );
		}
		else {
			$military = '<a href="map.php">' . translate( 'Map' ) . '</a>';
		}
		
		if( $selected == 'Military activity' ) {
			$military .= ' ' . translate( 'Visible armies' );
		}
		else {
			$military .= ' <a href="movement.php">' . translate( 'Visible armies' ) . '</a>';
		}

		if( $selected == 'Missions' ) {
			$military .= ' ' . translate( 'Missions' );
		}
		else {
			$military .= ' <a href="operations.php">' . translate( 'Missions' ) . '</a>';
		}
		
		if( $selected == 'Expeditions' ) {
			$military .= ' ' . translate( 'Expeditions' );
		}
		else {
			$military .= ' <a href="expeditions.php">' . translate( 'Expeditions' ) . '</a>';
		}

		if( $selected == 'Locations' ) {
			$military .= ' ' . translate( 'Locations' );
		}
		else {
			$military .= ' <a href="edit_locations.php">' . translate( 'Locations' ) . '</a>';
		}

		print( $military );
	}
	
	function update_faction_channels() {
		$query = "SELECT * " .
				"FROM faction ";
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$num = mysql_numrows( $result );
		$i = 0;
		while ( $i < $num ) {
			$query2 = "SELECT count(*) " .
					"FROM chat_channels " .
					"WHERE group_id = " . mysql_result( $result, $i, 'faction_id' );
			$result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
			$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
			if( $row2[ 'count(*)' ] == 0 ) {
				$query2 = "INSERT INTO chat_channels " .
						"( `group_id`, `name` ) " .
						"VALUES( " . mysql_result( $result, $i, 'faction_id' ) . ", 'General' )";
				mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
				$query2 = "SELECT channel_id " .
						"FROM chat_channels " .
						"WHERE group_id = " . mysql_result( $result, $i, 'faction_id' ) . " AND name = 'General'";
				$result2 = mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
				$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC );
				
				$query2 = "UPDATE chat " .
						"SET channel_id = " . $row2[ 'channel_id' ] . " " .
						"WHERE faction_id = " . mysql_result( $result, $i, 'faction_id' );
				mysql_query( $query2 ) or die( "Query failed : " . mysql_error() );
			}
			$i ++;
		}
	}
	
	function get_faction_color( $faction_id ) {
		$query = "SELECT color " .
				"FROM faction_colors " .
				"WHERE faction_id = " . $faction_id;
		$result2 = mysql_query($query) or die("Query failed : " . mysql_error());
		$row2 = mysql_fetch_array($result2, MYSQL_ASSOC);
		if( isset( $row2[ 'color' ] ) ) {
			$color = '<span class="faction-color" style="background-color: ' . $row2[ 'color' ] . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>';
		}
		else {
			$color = translate( 'None' );			
		}
		return $color;
	}
	
	function get_access_string( $level, $leader ) {
		if( $leader ) {
			return translate( 'Leader' );
		}
		elseif( $level == 0 ) {
			return translate( 'Member' );
		}
		elseif( $level == 1 ) {
			return translate( 'Assistant' );
		}
		elseif( $level == 5 ) {
			return translate( 'Organizer' );
		}
		elseif( $level == 10 ) {
			return translate( 'Vice Leader' );
		}
	}
	
	function print_locations_list() {
		$locations = get_locations();
		$printed = false;
		if( count( $locations ) > 0 ) {
?>
						<ul>
<?php
			$printed = true;
			foreach ( $locations AS $location ) {
?>
							<li><a href="javascript:void(null);" onclick="AOS.map.moveMapTo( <?php print( $location->x . ', ' . $location->y ); ?> )"><?php print( get_location_title( $location ) ); ?></a></li>
<?php	
			}			
		}
		
		$shared_locations = get_shared_locations();
		if( count( $shared_locations ) > 0 ) {
			if( !$printed ) {
?>
						<ul>
<?php
			}
			else {
?>
							<li class="dont-count-this">---------------------------------------</li>
<?php				
			}
			$printed = true;
			foreach ( $shared_locations AS $location ) {
?>
							<li class="dont-count-this"><a href="javascript:void(null);" onclick="AOS.map.moveMapTo( <?php print( $location->x . ', ' . $location->y ); ?> )"><?php print( get_location_title( $location ) ); ?></a></li>
<?php	
			}			
		}
				
		if( $printed ) {
?>
						</ul>
<?php
		}
	}
	
	function get_location_title( $location ) {
		$title = $location->title;
		if( $title == '' ) {
			$query2 = "SELECT name, ruler_id " .
					"FROM village " .
					"WHERE x = " . $location->x . " AND y = " . $location->y;
			$result2 = mysql_query( $query2 ) or die("Query failed : " . mysql_error());
			$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC);
			if( isset( $row2[ 'ruler_id' ] ) ) {
				if( $row2[ 'ruler_id' ] == -1 ) {
					$title = '<strong class="brown">' . translate( 'Independent village' ) . ' (' . $location->x . ', ' . $location->y . ')</strong>' ;
				}
				else {
					if( $row2[ 'ruler_id' ] == $_SESSION[ 'ruler_id' ] ) {
						$strong = '<strong class="green">';
					}
					else {
						$result3 = mysql_query( "SELECT faction_id " .
								"FROM faction_member " .
								"WHERE ruler_id = " . $row2[ 'ruler_id' ] . " AND requested = 0 AND invited = 0" ) 
									or die ( "Query failed: " . mysql_error() );
						$row3 = mysql_fetch_array($result3, MYSQL_ASSOC);
	
						$result4 = mysql_query( "SELECT faction_id " .
								"FROM faction_member " .
								"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " AND requested = 0 AND invited = 0" ) 
									or die ( "Query failed: " . mysql_error() );
						$row4 = mysql_fetch_array($result4, MYSQL_ASSOC);
						if( isset( $row3[ 'faction_id' ] ) && isset( $row4[ 'faction_id' ] ) && $row4[ 'faction_id' ] == $row3[ 'faction_id' ] ) {
							$strong = '<strong class="blue">';
						}
						else {
							$strong = '<strong class="red">';
						}
					}
					$title = $strong . $row2[ 'name' ] . '</strong>';
				}
			}	
			else {
				$title = '(' . $location->x . ', ' . $location->y . ')';
			}
		}
		return $title;
	}
	
	function get_locations() {
		$query = "SELECT * " .
	    		"FROM locations " .
	    		"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " " .
	    		"ORDER BY title ASC, y, x " .
	    		"LIMIT " . get_max_locations();
		$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
		$num = mysql_numrows( $result );
		$items = Array();
		while ( $row = mysql_fetch_object( $result ) ) {
			$items[] = $row;
		}
		return $items;
	}
	
	function get_shared_locations() {
		$query2 = "SELECT faction_id " .
				"FROM faction_member " .
				"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " AND invited = 0 AND requested = 0";
		$result2 = mysql_query( $query2 ) or die("Query failed : " . mysql_error());
		$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC);
		
		if( isset( $row2[ 'faction_id' ] ) ) {
			$query = "SELECT locations.* " .
		    		"FROM locations " .
		    		"JOIN faction_member ON faction_member.ruler_id = locations.ruler_id " . 
		    		"WHERE locations.ruler_id != " . $_SESSION[ 'ruler_id' ] . " AND faction_id = " . $row2[ 'faction_id' ] . " AND share = 1 " .
		    		"ORDER BY locations.title ASC, y, x";
			$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$num = mysql_numrows( $result );
			$items = Array();
			while ( $row = mysql_fetch_object( $result ) ) {
				$items[] = $row;
			}
			return $items;
		}
		else {
			return Array();
		}
	}
	
	function get_max_locations() {
		global $premium;
		if( $premium > 0 ) {
			return 20;
		}
		else {
			return 3;
		}
	}
	
	function get_location_link( $location ) {
		$title = $location->title;
		if( $title == '' ) {
			$query2 = "SELECT name, ruler_id " .
					"FROM village " .
					"WHERE x = " . $location->x . " AND y = " . $location->y;
			$result2 = mysql_query( $query2 ) or die("Query failed : " . mysql_error());
			$row2 = mysql_fetch_array( $result2, MYSQL_ASSOC);
			if( isset( $row2[ 'ruler_id' ] ) ) {
				if( $row2[ 'ruler_id' ] == -1 ) {
					$title = '<strong class="brown">' . translate( 'Independent village' ) . ' (' . $location->x . ', ' . $location->y . ')</strong>' ;
				}
				else {
					if( $row2[ 'ruler_id' ] == $_SESSION[ 'ruler_id' ] ) {
						$strong = '<strong class="green">';
					}
					else {
						$result3 = mysql_query( "SELECT faction_id " .
								"FROM faction_member " .
								"WHERE ruler_id = " . $row2[ 'ruler_id' ] . " AND requested = 0 AND invited = 0" ) 
									or die ( "Query failed: " . mysql_error() );
						$row3 = mysql_fetch_array($result3, MYSQL_ASSOC);

						$result4 = mysql_query( "SELECT faction_id " .
								"FROM faction_member " .
								"WHERE ruler_id = " . $_SESSION[ 'ruler_id' ] . " AND requested = 0 AND invited = 0" ) 
									or die ( "Query failed: " . mysql_error() );
						$row4 = mysql_fetch_array($result4, MYSQL_ASSOC);
						if( isset( $row3[ 'faction_id' ] ) && isset( $row4[ 'faction_id' ] ) && $row4[ 'faction_id' ] == $row3[ 'faction_id' ] ) {
							$strong = '<strong class="blue">';
						}
						else {
							$strong = '<strong class="red">';
						}
					}
					$title = $strong . $row2[ 'name' ] . '</strong>';
				}
			}	
			else {
				$title = '(' . $location->x . ', ' . $location->y . ')';
			}
		}
		return '<a href="../operations/map.php?x=' . ( $location->x - 20 ) . '&y=' . ( $location->y - 20 ) . '" title="Show on the map">' . $title . '</a>';
	}
	
	function print_officer_gather_info_page( $officer_id ) {
?>
					<?php transprint( 'Select location' ) ?>:<br />
					<select id="officer-gather-information-location">
						<option value="-1"><?php transprint( 'None' ); ?></option>
<?php
		$locations = get_locations();
		foreach( $locations AS $location ) {
?>
						<option value="<?php print( $location->location_id ); ?>"><?php print( get_location_title( $location ) ); ?></option>
<?php			
		}
?>
						<option value="-1">----------</option>
<?php
		$shared_locations = get_shared_locations();
		foreach( $shared_locations AS $location ) {
?>
						<option value="<?php print( $location->location_id ); ?>"><?php print( get_location_title( $location ) ); ?></option>
<?php			
		}
?>
					</select><br />
					<?php transprint( 'or' ); ?><br />
					<?php transprint( 'enter coordinates' ); ?>:<br />
					<input type="text" size="2" id="officer-gather-information-x" /> <input type="text" size="2" id="officer-gather-information-y" /><br />
					<br />
					<input type="hidden" id="officer-gather-information-id" value="<?php print( $officer_id ); ?>" />
					<input type="button" onclick="selectLocation();" value="<?php transprint( 'continue' ); ?>" />
<?php		
	}
	
	function get_bribe_cost( $population, $officer_id ) {
		if( $officer_id != -1 ) {
			$query = "SELECT persuasion " .
					"FROM officers " .
					"WHERE officer_id = $officer_id";
			$result = mysql_query( $query ) or die( "Query failed : " . mysql_error() );
			$row = mysql_fetch_array( $result, MYSQL_ASSOC );
			$persuasion = $row[ 'persuasion' ];
		}
		else {
			$persuasion = 0;
		}
		return round( ( 1600 + $population * 0.2 ) * ( 1 - ( 0.1 * $persuasion ) ) );
	}
	
	function aos_header( $title, $refresh = false ) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta http-equiv="Content-Style-Type" content="text/css" />
		<title>Ages of Strife: <?php transprint( $title ); ?></title>
		<link type="text/css" rel="stylesheet" href="../global/agesofstrife.css"></link>
		<?php ( $refresh ? print( '<meta http-equiv="refresh" content="600" />' ) : print( '' ) ); ?>
	</head>
	<body>
		<div id="root_container">
			<div align="center" id="header-image">
				<img class="header-dummy-image" src="../resources/dummy.gif" alt="Ages of Strife" border="0" />
			</div>
<?php
include( "../global/ads.php" );
?>
			<div id="container">
<?php
include( "../global/tabs.php" );
include_once( "../global/old_database_connection.php" );
?>
				<div id="main-content">
<?php
	}
	
	function aos_footer( $added_code = '' ) {
		global $charts, $show_ads;
?>
				</div>
				<div class="text-center">
					<small>
						<?php transprint( 'Contact' ); ?>: <a href="mailto:contact@agesofstrife.com">contact@agesofstrife.com</a> - <?php transprint( 'Parts of AoS are open source, you can find them' ); ?> <a href="http://opensource.bastiaangrutters.nl"><?php transprint( 'here' ); ?></a>.
					</small>
				</div>
			</div>
		</div>
		<script type="text/javascript" src="../global/merge_javascript.php?version=<?php require('../global/merge_javascript.php'); ?>"></script>
<?php
		print( $added_code );
?>
	</body>
</html>
<?php		
	}
	
	function getMaxPopulation( $villageId ) {
		global $dal;
		$statement = $dal->prepare( "SELECT SUM( housing * ammount ) " .
				"FROM village_buildings " .
				"JOIN buildings ON buildings.building_id = village_buildings.building_id " .
				"WHERE ( buildings.building_id = 26 OR buildings.building_id = 27 OR buildings.building_id = 28 ) AND village_id = :village_id" );
		$statement->bindParam( ':village_id', $villageId, PDO::PARAM_INT );
		$houses = $dal->getValue( $statement );

		$statement = $dal->prepare( "SELECT ammount " .
				"FROM village_buildings " .
				"WHERE building_id = 29 AND village_id = :village_id" );
		$statement->bindParam( ':village_id', $villageId, PDO::PARAM_INT );
		$housesMultiplier = 1;
		if( $dal->getValue( $statement ) > 0 ) {
			$housesMultiplier += 0.5;
		}

		$statement = $dal->prepare( 'SELECT ruler_id, focus ' .
				'FROM village ' .
				'WHERE village_id = :village_id' );
		$statement->bindParam( ':village_id', $villageId, PDO::PARAM_INT );
		$village = $dal->getObject( $statement );
		if( $village->focus == 'housing' ) {
			$housesMultiplier += 0.1;
		}
		elseif( $village->focus == 'coal' || $village->focus == 'iron' ) {
			$housesMultiplier -= 0.1;
		}
		
		if( isset( $village->ruler_id ) && $village->ruler_id != -1 ) {
			$statement = $dal->prepare( 'SELECT housing_support ' .
					'FROM faction ' .
					'JOIN faction_member ON faction_member.faction_id = faction.faction_id ' .
					'WHERE ruler_id = :ruler_id AND invited = 0 AND requested = 0' );
			$statement->bindParam( ':ruler_id', $village->ruler_id, PDO::PARAM_INT );
			$housingSupport = $dal->getValue( $statement );
			if( isset( $housingSupport ) && $housingSupport != 0 ) {
				$housesMultiplier += 0.1;
			}
		}
		
		return round( $houses * $housesMultiplier );
	}
	
	function getQueueLength() {
		global $premium;
		if( $premium > 0 ) {
			return 9;
		}
		else {
			return 3;
		}
	}
	
	function printOfficerRankIcon( $rank ) {
		if( $rank == 0 ) {
			$rankClass = "second-lieutenant";
		}
		elseif( $rank == 1 ) {
			$rankClass = "first-lieutenant";
		}
		elseif( $rank == 2 ) {
			$rankClass = "captain";
		}
		elseif( $rank == 3 ) {
			$rankClass = "major";
		}
		elseif( $rank == 4 ) {
			$rankClass = "lieutenant-colonel";
		}
		elseif( $rank == 5 ) {
			$rankClass = "colonel";
		}
		elseif( $rank == 6 ) {
			$rankClass = "general";
		}
		elseif( $rank == 7 ) {
			$rankClass = "field-marshal";
		}
		else {
			$rankClass = '';
		}
?>
				<div class="officer-rank-icon <?php print( $rankClass ); ?>">
					<img src="../resources/dummy.gif" />
				</div>
<?php		
	}
	
	function printMedals( $userId ) {
		$query = "SELECT * " .
			"FROM medals " .
			"WHERE user_id = $userId " .
			"ORDER BY timestamp DESC, `value` DESC";
		$result = mysql_query($query) or die("Query failed : " . mysql_error());
		$num = mysql_numrows($result);
		$i = 0;
		while ($i < $num) {
			if( substr( mysql_result( $result, $i, 'title' ), strlen( mysql_result( $result, $i, 'title' ) ) - 14 ) == 'campaign medal' ) {
				$class = 'campaign-medal';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Infantry branch insignia' ) {
				$class = 'infantry-branch-insignia';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Cavalry branch insignia' ) {
				$class = 'cavalry-branch-insignia';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Artillery branch insignia' ) {
				$class = 'artillery-branch-insignia';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Military bronze star' ) {
				$class = 'military-bronze-star';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Military silver star' ) {
				$class = 'military-silver-star';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Military gold star' ) {
				$class = 'military-gold-star';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Economic bronze star' ) {
				$class = 'economic-bronze-star';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Economic silver star' ) {
				$class = 'economic-silver-star';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Economic gold star' ) {
				$class = 'economic-gold-star';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Expander medal' ) {
				$class = 'expander-medal';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Grand expander medal' ) {
				$class = 'grand-expander-medal';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Engineer branch insignia' ) {
				$class = 'engineer-branch-insignia';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Research branch insignia' ) {
				$class = 'research-branch-insignia';
			}
			elseif( mysql_result( $result, $i, 'title' ) == 'Peoples protector ribbon' ) {
				$class = 'peoples-protector-ribbon';
			}
			else {
				$class = 'custom-medal';
			}
?>
					<div class="medal <?php print( $class ); ?>">
						<img src="/resources/dummy.gif" alt="<?php transprint( mysql_result( $result, $i, 'title' ) ); ?>" />
					</div>
<?php			
			$i ++;
		}
?>
					<div class="medal-closing">
						&nbsp;
					</div>
<?php			
	}
	
	function printVillageMap( $villageId, $title = '' ) {
		global $dal;
		
		$currentTurn = getCurrentTurn();

		$statement = $dal->prepare( 'SELECT season ' .
				'FROM game ' .
				'LIMIT 1' );
		$season = $dal->getValue( $statement );
		if( $season == 0 ) {
			$seasonModifier = '-winter';
		}
		elseif( $season == 2 ) {
			$seasonModifier = '-summer';
		}
		elseif( $season == 3 ) {
			$seasonModifier = '-autumn';
		}
		else {
			$seasonModifier = '';
		}
		
		$statement = $dal->prepare( 'SELECT SUM( ammount * space ) ' .
				'FROM village_buildings ' .
				'JOIN buildings ON buildings.building_id = village_buildings.building_id ' .
				'WHERE village_id = :village_id AND space > 0' );
		$statement->bindParam( ':village_id', $villageId, PDO::PARAM_INT );
		$usedSpace = $dal->getValue( $statement );

		$statement = $dal->prepare( 'SELECT space ' .
				'FROM village_queue ' .
				'JOIN buildings ON buildings.building_id = village_queue.building_id ' .
				'WHERE village_id = :village_id AND time != -1' );
		$statement->bindParam( ':village_id', $villageId, PDO::PARAM_INT );
		$addedSpace = $dal->getValue( $statement );
		if( isset( $addedSpace ) ) {
			$usedSpace += $addedSpace;
		}

		$statement = $dal->prepare( 'SELECT space, village_map_direction, x, y, village.ruler_id, faction_id, militia ' .
				'FROM village 
				LEFT JOIN faction_member ON faction_member.ruler_id = village.ruler_id AND requested = 0 AND invited = 0 ' .
				'WHERE village_id = :village_id' );
		$statement->bindParam( ':village_id', $villageId, PDO::PARAM_INT );
		$villageObject = $dal->getObject( $statement );
		$space = $villageObject->space;
		$villageDirection = $villageObject->village_map_direction;

		// Check if we need to add smoke (during battle and occupation) 
		$statement = $dal->prepare( 'SELECT army.ruler_id, faction_id ' .
				'FROM army 
				LEFT JOIN faction_member ON faction_member.ruler_id = army.ruler_id AND requested = 0 AND invited = 0 ' .
				'WHERE actual_x + 0.5 > :x AND actual_x - 0.5 < :x AND actual_y + 0.5 > :y AND actual_y - 0.5 < :y' );
		$statement->bindParam( ':x', $villageObject->x, PDO::PARAM_INT );
		$statement->bindParam( ':y', $villageObject->y, PDO::PARAM_INT );
		$armies = $dal->getArrayOfObjects( $statement );
		
		$militia = ( $villageObject->militia >= $currentTurn );
		$enemy = false;
		$friendly = false;
		foreach( $armies AS $army ) {
			if( ( isset( $army->faction_id ) && isset( $villageObject->faction_id ) && $villageObject->faction_id != $army->faction_id ) || 
				( !isset( $army->faction_id ) || !isset( $villageObject->faction_id ) ) && $villageObject->ruler_id != $army->ruler_id ) {
				$enemy = true;
			}
			else {
				$friendly = true;
			}
		}
?>
					<div class="blok">
<?php
		if( $title != '' ) {
?>
						<?php print( $title ); ?><br />
<?php			
		}	
?>					
						<div class="village-map">
<?php
		if( $enemy || $friendly || $militia ) {
?>
							<div class="village-status-message">
<?php
			if( $enemy && ( $friendly || $militia ) ) {
?>
				<strong><?php transprint( 'There is a battle going on' ); ?></strong>
<?php
			}
			elseif( $friendly ) {
?>
				<strong class="green"><?php transprint( 'Guarded by friendly forces' ); ?></strong>
<?php
			}
			elseif( $militia ) {
?>
				<strong class="green"><?php transprint( 'Guarded by a militia' ); ?></strong>
<?php
			}
			else {
?>
				<strong class="red"><?php transprint( 'Occupied by hostile forces' ); ?></strong>
<?php
			}
?>
							</div>
<?php
			if( $enemy ) { 
?>
							<div class="smoke-overlay<?php print( ( $friendly || $militia ) ? '' : ' transparent' ); ?>"> </div>
<?php			
			}
		}
		
		$imageVariation = Array();
		$imageVariation[ 'nature' ] = 18;
		$imageVariation[ 'farms' ] = 4;
		$imageVariation[ 'space' ] = 1;
		$imageVariation[ 'houses' ] = 4;
		$imageVariation[ 'other' ] = 1;
		$imageVariation[ 'coal' ] = 3;
		$imageVariation[ 'iron' ] = 3;
		
		$spaceLeft = Array();
		$spaceLeft[ 'nature' ] = 180 - ( $space + $usedSpace );
		$spaceLeft[ 'space' ] = $space;
		$spaceLeft[ 'other' ] = 0;
		
		$statement = $dal->prepare( 'SELECT ammount * space ' .
				'FROM village_buildings ' .
				'JOIN buildings ON buildings.building_id = village_buildings.building_id ' .
				'WHERE buildings.building_id = :building_id AND village_id = :village_id' );
		$buildingId = 1; // Farm
		$statement->bindParam( ':village_id', $villageId, PDO::PARAM_INT );
		$statement->bindParam( ':building_id', $buildingId, PDO::PARAM_INT );
		$spaceLeft[ 'farms' ] = $dal->getValue( $statement );
		$buildingId = 9; // Large farm
		$spaceLeft[ 'farms' ] += $dal->getValue( $statement );
		$buildingId = 16; // Farm hub
		$spaceLeft[ 'farms' ] += $dal->getValue( $statement );
	
		$buildingId = 26; // Small houses
		$spaceLeft[ 'houses' ] = $dal->getValue( $statement );
		$buildingId = 27; // Medium houses
		$spaceLeft[ 'houses' ] += $dal->getValue( $statement );
		$buildingId = 28; // Large houses
		$spaceLeft[ 'houses' ] += $dal->getValue( $statement );
		
		$buildingId = 2; // Coal mine
		$spaceLeft[ 'coal' ] = $dal->getValue( $statement );
		$buildingId = 10; // Large coal min
		$spaceLeft[ 'coal' ] += $dal->getValue( $statement );
		$buildingId = 20; // Coal mine shaft
		$spaceLeft[ 'coal' ] += $dal->getValue( $statement );
		
		$buildingId = 3; // Iron mine
		$spaceLeft[ 'iron' ] = $dal->getValue( $statement );
		$buildingId = 11; // Large iron min
		$spaceLeft[ 'iron' ] += $dal->getValue( $statement );
		$buildingId = 18; // Iron mine shaft
		$spaceLeft[ 'iron' ] += $dal->getValue( $statement );

		$buildingId = 7; // Doctors office
		$spaceLeft[ 'doctor' ] = $dal->getValue( $statement );
		
		$buildingId = 6; // Recruitment office
		$spaceLeft[ 'recruitment' ] = $dal->getValue( $statement );
		
		$buildingId = 24; // Military academy
		$spaceLeft[ 'military' ] = $dal->getValue( $statement );
		
		$buildingId = 22; // Barracks
		$spaceLeft[ 'barracks' ] = $dal->getValue( $statement );
		
		$buildingId = 14; // Marketplace
		$spaceLeft[ 'market' ] = $dal->getValue( $statement );
		
		$buildingId = 17; // Iron melter
		$spaceLeft[ 'iron_melter' ] = $dal->getValue( $statement );
		
		$buildingId = 19; // Charcoal burner
		$spaceLeft[ 'charcoal' ] = $dal->getValue( $statement );
		
		$buildingId = 0; // Church
		$spaceLeft[ 'church' ] = $dal->getValue( $statement );
		
		$buildingId = 23; // Warehouse
		$spaceLeft[ 'warehouse' ] = $dal->getValue( $statement );
		
		$buildingId = 5; // City walls
		$hasWalls = ( $dal->getValue( $statement ) > 0 );
		
		$buildingId = 4; // Guard towers
		$hasTowers = ( $dal->getValue( $statement ) > 0 );
		
		$buildingId = 8; // Canons
		$hasCanons = ( $dal->getValue( $statement ) > 0 );
		
		$buildingId = 15; // Irrigation
		$irrigation = ( $dal->getValue( $statement ) > 0 ) ? '-irrigation' : '';
		
		$statement = $dal->prepare( 'SELECT * ' .
				'FROM village_queue ' .
				'JOIN buildings ON buildings.building_id = village_queue.building_id ' .
				'WHERE village_id = :village_id AND time != -1 AND destroy = 0' );
		$statement->bindParam( ':village_id', $villageId, PDO::PARAM_INT );
		$underConstruction = $dal->getObject( $statement );
		
		if( isset( $underConstruction ) && $underConstruction->space > 0 ) {
			$underConstructionSpace = $underConstruction->space;
			if( $underConstruction->food_income > 0 ) {
				$underConstructionType = 'farms';
				$spaceLeft[ 'farms' ] += $underConstruction->space;
			}
			elseif( $underConstruction->coal_income > 0 ) {
				$underConstructionType = 'coal';
				$spaceLeft[ 'coal' ] += $underConstruction->space;
			}
			elseif( $underConstruction->iron_income > 0 ) {
				$underConstructionType = 'iron';
				$spaceLeft[ 'iron' ] += $underConstruction->space;
			}
			elseif( $underConstruction->housing > 0 ) {
				$underConstructionType = 'houses';
				$spaceLeft[ 'houses' ] += $underConstruction->space;
			}
			else {
				$underConstructionType = 'other';
				$spaceLeft[ 'other' ] += $underConstruction->space;
			}
		}
		else {
			$underConstructionSpace = 0;
			$underConstructionType = '';
		}
		
		// Build the city walls if present
		if( $hasWalls ) {
			$startAt = 0;
			$found = false;
			$remainingNature = $spaceLeft[ 'nature' ];
			while( !$found ) {
				$deduct = ( 14 - ( $startAt * 2 ) ) * 2 + ( 11 - ( $startAt * 2 ) ) * 2;
				if( $remainingNature >= $deduct ) {
					$remainingNature -= $deduct;
					$startAt ++;
				}
				else {
					$found = true;
				}
			}
			$y = $x = $startAt;
			$yBottom = 11 - $y;
			$xRight = 14 - $x;
			if( $hasCanons ) {
				$classAdd = '-canon';
			}
			elseif( $hasTowers ) {
				$classAdd = '-tower';
			}
			else {
				$classAdd = '';
			}
			for( $i = 0; $i < 15 - $startAt * 2; $i ++ ) {
				if( $i == 0 ) {
					// Place left corners
?>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-left-top<?php print( $classAdd ); ?>" style="top: <?php print( 22 + $y * 25 - ( $classAdd != '' ? 25 : 0 ) ); ?>px; left: <?php print( ( 215 - 18 * $y ) + ( $x + $i ) * 32  ); ?>px; z-index: <?php print( ( $x + $i ) * 2 + $y * 2 ); ?>;">
							</div>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-left-bottom<?php print( $classAdd ); ?>" style="top: <?php print( 15 + $yBottom * 25 ); ?>px; left: <?php print( ( 215 - 18 * $yBottom ) + ( $x + $i ) * 32  ); ?>px; z-index: <?php print( ( $x + $i ) * 2 + $yBottom * 2 + 1 ); ?>;">
							</div>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-left-bottom-part-2" style="top: <?php print( 15 + $yBottom * 25 ); ?>px; left: <?php print( ( 215 - 18 * $yBottom ) + ( $x + $i ) * 32  ); ?>px; z-index: <?php print( ( $x + $i ) * 2 + $yBottom * 2 - 1 ); ?>;">
							</div>
<?php					
				}
				elseif( $i == 14 - $startAt * 2 ) {
					// Place right corners
?>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-right-top<?php print( $classAdd ); ?>" style="top: <?php print( 22 + $y * 25 - ( $classAdd != '' ? 25 : 0 ) ); ?>px; left: <?php print( ( 231 - 18 * $y ) + ( $x + $i ) * 32  ); ?>px; z-index: <?php print( ( $x + $i ) * 2 + $y * 2 + 1 ); ?>;">
							</div>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-right-top-part-2" style="top: <?php print( 22 + $y * 25 ); ?>px; left: <?php print( ( 231 - 18 * $y ) + ( $x + $i ) * 32  ); ?>px; z-index: <?php print( ( $x + $i ) * 2 + $y * 2 - 1 ); ?>;">
							</div>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-right-bottom<?php print( $classAdd ); ?>" style="top: <?php print( 15 + $yBottom * 25 ); ?>px; left: <?php print( ( 234 - 18 * $yBottom ) + ( $x + $i ) * 32  ); ?>px; z-index: <?php print( ( $x + $i ) * 2 + $yBottom * 2 + 1 ); ?>;">
							</div>
<?php					
				}
				elseif( $i == ( 14 - ( $startAt * 2 ) ) / 2 ) {
					// Place the gate
?>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-gate" style="top: <?php print( $y * 25 - 10 ); ?>px; left: <?php print( ( 252 - 18 * $y ) + ( $x + $i ) * 32  ); ?>px; z-index: <?php print( ( $x + $i ) * 2 + $y * 2 ); ?>;">
							</div>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-gate" style="top: <?php print( 15 + $yBottom * 25 ); ?>px; left: <?php print( ( 234 - 18 * $yBottom ) + ( $x + $i ) * 32  ); ?>px; z-index: <?php print( ( $x + $i ) * 2 + $yBottom * 2 + 1 ); ?>;">
							</div>
<?php					
				}
				else {
					// Place wall part bottom and top
?>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-horizontal" style="top: <?php print( $y * 25 - 10 ); ?>px; left: <?php print( ( 252 - 18 * $y ) + ( $x + $i ) * 32  ); ?>px; z-index: <?php print( ( $x + $i ) * 2 + $y * 2 ); ?>;">
							</div>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-horizontal" style="top: <?php print( 15 + $yBottom * 25 ); ?>px; left: <?php print( ( 234 - 18 * $yBottom ) + ( $x + $i ) * 32  ); ?>px; z-index: <?php print( ( $x + $i ) * 2 + $yBottom * 2 + 1 ); ?>;">
							</div>
<?php					
				}
			}
			for( $i = 1; $i < 11 - $startAt * 2; $i ++ ) {
				// Place left and right walls
?>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-vertical" style="top: <?php print( 13 + ( $y + $i ) * 25 ); ?>px; left: <?php print( ( 212 - 18 * ( $y + $i ) ) + $x * 32  ); ?>px; z-index: <?php print( $x * 2 + ( $y + $i ) * 2 ); ?>;">
							</div>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> village-map-wall-vertical" style="top: <?php print( 15 + ( $y + $i ) * 25 ); ?>px; left: <?php print( ( 245 - 18 * ( $y + $i ) ) + $xRight * 32  ); ?>px; z-index: <?php print( $xRight * 2 + ( $y + $i ) * 2 + 1 ); ?>;">
							</div>
<?php					
			}
		}

		$variation = 1;
		$done = false;
		$direction = $villageDirection;
		$directionNextStep = $direction - 1;
		if( $directionNextStep == -1 ) {
			$directionNextStep = 3;
		}
		
		if( $direction == 0 ) {
			$x = -1;
			$y = 0;
		}
		elseif( $direction == 1 ) {
			$y = -1;
			$x = 14;
		}
		elseif( $direction == 2 ) {
			$y = 11;
			$x = 15;
		}
		else {
			$y = 12;
			$x = 0;
		}
		
		$border = 0;
		$lastOne = 'nature';
		
		while( !$done ) {
			if( $direction == 0 ) {
				$x ++;
				if( $x >= 15 - $border || ( $directionNextStep == $direction && $x >= 14 - $border ) ) {
					if( $directionNextStep == $direction ) {
						$border ++;
						$y = $border - 1;
					}
					else {
						$y = $border;
					}
					$x = 14 - $border;
					$direction ++;
				}
			}
			if( $direction == 1 ) {
				$y ++;
				if( $y >= 12 - $border || ( $directionNextStep == $direction && $y >= 11 - $border ) ) {
					if( $directionNextStep == $direction ) {
						$border ++;
						$x = 15 - $border;
					}
					else {
						$x = 14 - $border;
					}
					$y = 11 - $border;
					$direction ++;
				}
			}
			if( $direction == 2 ) {
				$x --;
				if( ( $directionNextStep != $direction && $x <= ( $border - 1 ) ) || ( $directionNextStep == $direction && $x <= $border ) ) {
					if( $directionNextStep == $direction ) {
						$border ++;
						$y = 12 - $border;
					}
					else {
						$y = 11 - $border;
					}
					$x = $border;
					$direction ++;
				}
			}
			if( $direction == 3 ) {
				$y --;
				if( ( $directionNextStep != $direction && $y <= $border - 1 ) || ( $directionNextStep == $direction && $y <= $border ) ) {
					if( $directionNextStep == $direction ) {
						$border ++;
						$x = $border;
					}
					else {
						$x = $border + 1;
					}
					$y = $border;
					$direction = 0;
				}
			}
	
			$variation ++;
			
			if( $spaceLeft[ 'nature' ] > 0 ) {
				$spaceLeft[ 'nature' ] --;
				if( $lastOne != 'nature' ) {
					$variation = 1;
					$lastOne = 'nature';
				}
				if( $variation > $imageVariation[ 'nature' ] ) {
					$variation = 1;
				}
				if( $x == 7 ) {
					$class = 'village-map-road';
				}
				elseif( $variation == 1 ) {
					$class = 'village-map-nature';
				}
				else {
					$class = 'village-map-nature-' . $variation;
				}
			}
			elseif( $x == 7 && $y == 6 && $spaceLeft[ 'church' ] > 0 ) {
				$spaceLeft[ 'church' ] --;
				$variation = 1;
				$class = 'village-map-church';
			}
			elseif( $spaceLeft[ 'space' ] > 0 ) {
				$spaceLeft[ 'space' ] --;
				if( $lastOne != 'space' ) {
					$variation = 1;
					$lastOne = 'space';
				}
				if( $variation > $imageVariation[ 'space' ] ) {
					$variation = 1;
				}
				if( $x == 7 ) {
					$class = 'village-map-road';
				}
				elseif( $variation == 1 ) {
					$class = 'village-map-space';
				}
				else {
					$class = 'village-map-space-' . $variation;
				}
			}
			elseif( $spaceLeft[ 'farms' ] > 0 ) {
				$spaceLeft[ 'farms' ] --;
				if( $lastOne != 'farms' ) {
					$variation = 1;
					$lastOne = 'farms';
				}
				if( $underConstructionType == 'farms' && $underConstructionSpace > 0 ) {
					$class = 'village-map-construction';
					$underConstructionSpace --;
				}
				else {
					if( $variation > $imageVariation[ 'farms' ] ) {
						$variation = 1;
					}
					if( $variation == 1 ) {
						$class = 'village-map-farm' . $irrigation;
					}
					else {
						$class = 'village-map-farm-' . $variation . $irrigation;
					}
					
				}
			}
			elseif( $spaceLeft[ 'iron' ] > 0 ) {
				$spaceLeft[ 'iron' ] --;
				if( $lastOne != 'iron' ) {
					$variation = 1;
					$lastOne = 'iron';
				}
				if( $underConstructionType == 'iron' && $underConstructionSpace > 0 ) {
					$class = 'village-map-construction';
					$underConstructionSpace --;
				}
				else {
					if( $variation > $imageVariation[ 'iron' ] ) {
						$variation = 1;
					}
					if( $variation == 1 ) {
						$class = 'village-map-iron';
					}
					else {
						$class = 'village-map-iron-' . $variation;
					}
				}
			}
			elseif( $spaceLeft[ 'coal' ] > 0 ) {
				$spaceLeft[ 'coal' ] --;
				if( $lastOne != 'coal' ) {
					$variation = 1;
					$lastOne = 'coal';
				}
				if( $underConstructionType == 'coal' && $underConstructionSpace > 0 ) {
					$class = 'village-map-construction';
					$underConstructionSpace --;
				}
				else {
					if( $variation > $imageVariation[ 'coal' ] ) {
						$variation = 1;
					}
					if( $variation == 1 ) {
						$class = 'village-map-coal';
					}
					else {
						$class = 'village-map-coal-' . $variation;
					}
				}
			}
			elseif( $spaceLeft[ 'houses' ] > 0 ) {
				$spaceLeft[ 'houses' ] --;
				if( $lastOne != 'houses' ) {
					$variation = 1;
					$lastOne = 'houses';
				}
				if( $underConstructionType == 'houses' && $underConstructionSpace > 0 ) {
					$class = 'village-map-construction';
					$underConstructionSpace --;
				}
				else {
					if( $variation > $imageVariation[ 'houses' ] ) {
						$variation = 1;
					}
					if( $variation == 1 ) {
						$class = 'village-map-houses';
					}
					else {
						$class = 'village-map-houses-' . $variation;
					}
				}
			}
			elseif( $spaceLeft[ 'recruitment' ] > 0 ) {
				$spaceLeft[ 'recruitment' ] --;
				$variation = 1;
				$class = 'village-map-recruitment';
			}
			elseif( $spaceLeft[ 'charcoal' ] > 0 ) {
				$spaceLeft[ 'charcoal' ] --;
				$variation = 1;
				$class = 'village-map-charcoal-burner';
			}
			elseif( $spaceLeft[ 'doctor' ] > 0 ) {
				$spaceLeft[ 'doctor' ] --;
				$variation = 1;
				$class = 'village-map-doctor';
			}
			elseif( $spaceLeft[ 'barracks' ] > 0 ) {
				$spaceLeft[ 'barracks' ] --;
				$variation = 1;
				$class = 'village-map-barracks';
			}
			elseif( $spaceLeft[ 'iron_melter' ] > 0 ) {
				$spaceLeft[ 'iron_melter' ] --;
				$variation = 1;
				$class = 'village-map-iron-melter';
			}
			elseif( $spaceLeft[ 'military' ] > 0 ) {
				$spaceLeft[ 'military' ] --;
				$variation = 1;
				$class = 'village-map-military';
			}
			elseif( $spaceLeft[ 'market' ] > 0 ) {
				$spaceLeft[ 'market' ] --;
				$variation = 1;
				$class = 'village-map-market';
			}
			elseif( $spaceLeft[ 'warehouse' ] > 0 ) {
				$spaceLeft[ 'warehouse' ] --;
				$variation = 1;
				$class = 'village-map-warehouse';
			}
			else {
				// all remaining squares are filled with this one
				if( $lastOne != 'other' ) {
					$variation = 1;
					$lastOne = 'other';
				}
				if( $underConstructionType == 'other' && $underConstructionSpace > 0 ) {
					$underConstructionSpace --;
					$class = 'village-map-construction';
				}
				else {
					if( $variation > $imageVariation[ 'other' ] ) {
						$variation = 1;
					}
					if( $variation == 1 ) {
						$class = 'village-map-other';
					}
					else {
						$class = 'village-map-other-' . $variation;
					}
				}
			}
?>
							<div class="village-map-tile<?php print( $seasonModifier ); ?> <?php print( $class ); ?>" style="top: <?php print( 15 + $y * 25 ); ?>px; left: <?php print( ( 234 - 18 * $y ) + $x * 32  ); ?>px; z-index: <?php print( $x * 2 + $y * 2 ); ?>;">
							</div>
<?php
			if( $directionNextStep == 3 && $x == 5 && $y == 6 ) {
				$done = true;
			}
			elseif( $directionNextStep == 0 && $x == 8 && $y == 5 ) {
				$done = true;
			}
			elseif( $directionNextStep == 1 && $x == 9 && $y == 5 ) {
				$done = true;
			}
			elseif( $directionNextStep == 2 && $x == 6 && $y == 6 ) {
				$done = true;
			}
		}
?>
						</div>
					</div>
					<br />
<?php	
	}
	
	function getSeasonString() {
		global $dal;
		$statement = $dal->prepare( 'SELECT season ' .
				'FROM game ' .
				'LIMIT 1' );
		$season = $dal->getValue( $statement );
		if( $season == 0 ) {
			return 'Winter';
		}
		if( $season == 1 ) {
			return 'Spring';
		}
		if( $season == 2 ) {
			return 'Summer';
		}
		if( $season == 3 ) {
			return 'Autumn';
		}
		else {
			return 'Unknown';
		}
	}
	
	function tryToIncreaseRank( $officerId, $rank, $ranking ) {
		global $dal;
		
		$rank ++;
		if( 2 + $ranking < $rank ) {
			return false;
		}
		else {
			$statement = $dal->prepare( 'UPDATE officers ' .
					'SET rank = :rank ' .
					'WHERE officer_id = :officer_id' );
			$statement->bindParam( ':rank', $rank, PDO::PARAM_INT );
			$statement->bindParam( ':officer_id', $officerId, PDO::PARAM_INT );
			$dal->execute( $statement );
			checkOfficerCommandChainPosition( $officerId );
			return true;
		}
	}
	
	function increaseRankOfficer( $officerId, $requestedSize ) {
		global $dal;
		$statement = $dal->prepare( 'SELECT rank, ranking ' .
				'FROM officers ' .
				'WHERE officer_id = :officer_id' );
		$statement->bindParam( ':officer_id', $officerId, PDO::PARAM_INT );
		$officer = $dal->getObject( $statement );
		
		$maxSize = 10 * pow( 5, ( $officer->rank + 1 ) );
		$impossible = false;
		$rankedIncreased = false;
		while ( $maxSize < $requestedSize && !$impossible ) {
			if( !tryToIncreaseRank( $officerId, $officer->rank, $officer->ranking ) ) {
				$impossible = true;
			}
			else {
				$rankedIncreased = true;
				$officer->rank ++;
				$maxSize = 10 * pow( 5, ( $officer->rank + 1 ) );
			}
		}
		
		if( $impossible ) {
			$text = 'Officer can not be promoted high enough to add this amount of soldiers.';
		}
		elseif( $rankedIncreased ) {
			$text = 'Officer promoted, to allow adding this number of soldiers.';
		}
		else {
			$text = '';
		}
		return $text;
	}
	
	function getHighestSubordinateRank( $officerId ) {
		global $dal;
		$statement = $dal->prepare( 'SELECT MAX(rank) 
			FROM officers 
			WHERE parent_officer_id = :officer_id' );
		$statement->bindParam( ':officer_id', $officerId, PDO::PARAM_INT );
		return $dal->getValue( $statement );
	}
	
	function printChainOfCommand( $officerId = -1 ) {
		global $dal;
		$statement = $dal->prepare( 'SELECT * 
			FROM officers 
			WHERE parent_officer_id = :officer_id AND ruler_id = :ruler_id 
			ORDER BY rank DESC, experience DESC, name' );
		$statement->bindParam( ':officer_id', $officerId, PDO::PARAM_INT );
		$statement->bindParam( ':ruler_id', $_SESSION[ 'ruler_id' ], PDO::PARAM_INT );
		$officers = $dal->getArrayOfObjects( $statement );
		if( count( $officers ) > 0 ) {
			foreach( $officers AS $officer ) {
				$possibleCommanders = getPossibleCommanders( $officer->rank );
?>
					<div class="officer-container">
						<?php printOfficerRankIcon( $officer->rank ); ?> <?php transprint( getOfficerRankString( $officer->rank ) ); ?> <a href="officer.php?name=<?php print( $officer->name ); ?>"><strong><?php print( $officer->name ); ?></strong></a><br class="clear" />
<?php 
				if( count( $possibleCommanders ) > 0 ) {
?>
						<form method="post" action="set_commanding_officer.php">
							<input type="hidden" name="officer_id" value="<?php print( $officer->officer_id ); ?>" />
							<?php transprint( 'Serves under' ); ?> <select name="commander" onchange="this.parentNode.submit();">
								<option value="-1"><?php transprint( 'None' ); ?></option>
<?php
					foreach( $possibleCommanders AS $possibleCommander ) {
?>
								<option <?php print( $officer->parent_officer_id == $possibleCommander->officer_id ? 'selected="selected" ' : '' ); ?>value="<?php print( $possibleCommander->officer_id ); ?>"><?php transprint( getOfficerRankString( $possibleCommander->rank ) ); ?> <?php print( $possibleCommander->name ); ?></option>
<?php
					}
?>
							</select>
						</form><br />
<?php						
				}

				$statement = $dal->prepare( 'SELECT scout, infantry, cavalry, artillery, name 
					FROM army 
					WHERE officer_id = :officer_id' );
				$statement->bindParam( ':officer_id', $officer->officer_id, PDO::PARAM_INT );
				$army = $dal->getObject( $statement );
				if( isset( $army ) ) {
					$armySize = '<a href="army.php?name=' . $army->name . '">' . $army->name . '</a> (' . number_format( $army->scout + $army->infantry + $army->cavalry + $army->artillery ) . ')';
				}
				else {
					$armySize = translate( 'None' );
				}
?>
						<?php transprint( 'Army' ); ?>: <?php print( $armySize ); ?><br />
						<?php printChainOfCommand( $officer->officer_id ); ?>
					</div>
<?php 
			}
		}
	}
	
	function getPossibleCommanders( $rank ) {
		global $dal;
		$statement = $dal->prepare( 'SELECT * 
			FROM officers 
			WHERE rank > :rank AND ruler_id = :ruler_id 
			ORDER BY rank DESC, experience DESC, name' );
		$statement->bindParam( ':rank', $rank, PDO::PARAM_INT );
		$statement->bindParam( ':ruler_id', $_SESSION[ 'ruler_id' ], PDO::PARAM_INT );
		return $dal->getArrayOfObjects( $statement );
	}
	
	function getOfficerRankString( $rank ) {
        $rankString = 'Unknown';
		if( $rank == 0 ) {
        	$rankString = "2nd Lieutenant";
        }
        elseif( $rank == 1 ) {
        	$rankString = "1st Lieutenant";
        }
        elseif( $rank == 2 ) {
        	$rankString = "Captain";
        }
        elseif( $rank == 3 ) {
        	$rankString = "Major";
        }
        elseif( $rank == 4 ) {
        	$rankString = "Lieutenant-Colonel";
        }
        elseif( $rank == 5 ) {
        	$rankString = "Colonel";
        }
        elseif( $rank == 6 ) {
        	$rankString = "General";
        }
        elseif( $rank == 7 ) {
        	$rankString = "Field Marshal";
        }
        return $rankString;
	}
	
	function checkOfficerCommandChainPosition( $officerId ) {
		global $dal;
		$statement = $dal->prepare( 'SELECT rank, parent_officer_id 
			FROM officers 
			WHERE officer_id = :officer_id AND ruler_id = :ruler_id' );
		$statement->bindParam( ':officer_id', $officerId, PDO::PARAM_INT );
		$statement->bindParam( ':ruler_id', $_SESSION[ 'ruler_id' ], PDO::PARAM_INT );
		$officer = $dal->getObject( $statement );
		if( $officer ) {
			if( $officer->parent_officer_id != -1 ) {
				$statement = $dal->prepare( 'SELECT rank 
					FROM officers 
					WHERE officer_id = :officer_id' );
				$statement->bindParam( ':officer_id', $officer->parent_officer_id, PDO::PARAM_INT );
				if( $officer->rank > $dal->getValue( $statement ) ) {
					$statement = $dal->prepare( 'UPDATE officers 
						SET parent_officer_id = -1 
						WHERE officer_id = :officer_id' );
					$statement->bindParam( ':officer_id', $officerId, PDO::PARAM_INT );
					$dal->execute( $statement );
				}
			}
			$statement = $dal->prepare( 'SELECT officer_id, rank 
				FROM officers 
				WHERE parent_officer_id = :officer_id' );
			$statement->bindParam( ':officer_id', $officerId, PDO::PARAM_INT );
			$subordinateOfficers = $dal->getArrayOfObjects( $statement );
			
			$subordinateOfficerId = -1;
			$statement = $dal->prepare( 'UPDATE officers 
				SET parent_officer_id = -1 
				WHERE officer_id = :officer_id' );
			$statement->bindParam( ':officer_id', $subordinateOfficerId, PDO::PARAM_INT );
			foreach( $subordinateOfficers AS $subordinateOfficer ) {
				if( $subordinateOfficer->rank > $officer->rank ) {
					$subordinateOfficerId = $subordinateOfficer->officer_id;
					$dal->execute( $statement );
				}
			}
		}
	}
	
	function getHighestTravelTimeSubordinates( $officerId, $x, $y ) {
		global $dal;
		
		$highestTime = 0;
		
		// We gather the direct subordinate officers and their army ids (if any)
		$statement = $dal->prepare( 'SELECT army_id, army.officer_id
			FROM officers 
			LEFT JOIN army ON army.officer_id = officers.officer_id
			WHERE parent_officer_id = :officer_id' );
		$statement->bindParam( ':officer_id', $officerId, PDO::PARAM_INT );
		$subordinateOfficers = $dal->getArrayOfObjects( $statement );
		foreach( $subordinateOfficers AS $subordinateOfficer ) {
			if( isset( $subordinateOfficer->army_id ) ) {
				$time = getTravelTime( $subordinateOfficer->army_id, $x, $y );
				if( $time > $highestTime ) {
					$highestTime = $time;
				}
			}
			$time = getHighestTravelTimeSubordinates( $subordinateOfficer->officer_id, $x, $y );
			if( $time > $highestTime ) {
				$highestTime = $time;
			}
		}
		return $highestTime;
	}
	
	function setTravelSubordinates( $officerId, $armyId, $x, $y, $time ) {
		global $dal;
		
		$rank = -1;
		$orderType = 1; // Movement order
		$orderValue = $x; // First we need location
		$orderValue2 = $y; // First we need location
		$statementOrderRank = $dal->prepare( 'SELECT COUNT(*) 
			FROM army_orders 
			WHERE army_id = :army_id' );
		$statementOrderRank->bindParam( ':army_id', $armyId, PDO::PARAM_INT );
		$statementInsertOrder = $dal->prepare( 'INSERT INTO army_orders 
							( `army_id`, `order_type`, `order_value`, `order_value2`, `rank` ) 
							VALUES ( :army_id, :order_type, :order_value, :order_value2, :rank )' );
		$statementInsertOrder->bindParam( ':army_id', $armyId, PDO::PARAM_INT );
		$statementInsertOrder->bindParam( ':order_type', $orderType, PDO::PARAM_INT );
		$statementInsertOrder->bindParam( ':order_value', $orderValue, PDO::PARAM_INT );
		$statementInsertOrder->bindParam( ':order_value2', $orderValue2, PDO::PARAM_INT );
		$statementInsertOrder->bindParam( ':rank', $rank, PDO::PARAM_INT );
		
		$statementFollowing = $dal->prepare( 'SELECT army_id 
			FROM army 
			WHERE follow = :army_id AND NOT ruler_id = :ruler_id' );
		$statementFollowing->bindParam( ':army_id', $armyId, PDO::PARAM_INT );
		$statementFollowing->bindParam( ':ruler_id', $_SESSION[ 'ruler_id' ], PDO::PARAM_INT );
		
		if( $armyId == -1 ) {
			// We need to set this army as well
			$statement = $dal->prepare( 'SELECT army_id 
				FROM army 
				WHERE officer_id = :officer_id AND ruler_id = :ruler_id' );
			$statement->bindParam( ':officer_id', $officerId, PDO::PARAM_INT );
			$statement->bindParam( ':ruler_id', $_SESSION[ 'ruler_id' ], PDO::PARAM_INT );
			$army = $dal->getObject( $statement );
			if( isset( $army ) ) {
				$armyId = $army->army_id;
				$travelTime = getTravelTime( $army->army_id, $x, $y );
				$rank = $dal->getValue( $statementOrderRank );
				$dal->execute( $statementInsertOrder );
				$orderType = 2;
				$orderValue = $time - $travelTime;
				$orderValue2 = -1;
				$rank ++;
				if( $orderValue > 0 ) {
					$dal->execute( $statementInsertOrder );
				}
			}
		}
		// We gather the direct subordinate officers and their army ids (if any)
		$statement = $dal->prepare( 'SELECT army_id, army.officer_id
			FROM officers 
			LEFT JOIN army ON army.officer_id = officers.officer_id
			WHERE parent_officer_id = :officer_id' );
		$statement->bindParam( ':officer_id', $officerId, PDO::PARAM_INT );
		$subordinateOfficers = $dal->getArrayOfObjects( $statement );
		print_r( $subordinateOfficers );
		foreach( $subordinateOfficers AS $subordinateOfficer ) {
			if( isset( $subordinateOfficer->army_id ) ) {
				$armyId = $subordinateOfficer->army_id;
				$travelTime = getTravelTime( $armyId, $x, $y );
				$rank = $dal->getValue( $statementOrderRank );
				$orderType = 1; // Movement order
				$orderValue = $x; // We need the location
				$orderValue2 = $y; // We need the location
				$dal->execute( $statementInsertOrder );
				$orderType = 2;
				$orderValue = $time - $travelTime;
				$orderValue2 = -1;
				$rank ++;
				if( $orderValue > 0 ) {
					$dal->execute( $statementInsertOrder );
				}
				
				$armyIds = $dal->getArrayOfValues( $statementFollowing );
				foreach( $armyIds AS $armyId ) {
					$rank --;
					$orderType = 1; // Movement order
					$orderValue = $x; // We need the location
					$orderValue2 = $y; // We need the location
					$dal->execute( $statementInsertOrder );
					$orderType = 2;
					$orderValue = $time - $travelTime;
					$orderValue2 = -1;
					$rank ++;
					if( $orderValue > 0 ) {
						$dal->execute( $statementInsertOrder );
					}
				}
			}
			setTravelSubordinates( $subordinateOfficer->officer_id, $subordinateOfficer->army_id, $x, $y, $time );
		}
	}
}
?>
